1

I have an array containing the following data:

var arr = [30, "Chad", 400, 700, "Brian", "Zander", "allen", 43, 50]

I want to sort this array into an array containing just the numbers (from lowest to highest) and another array containing just the strings (in alphabetical order--the "a" in Allen is currently lowercase but still should go before the other names).

I assume I would use a for loop combined with an if/else statement but am not sure of the syntax. Any help would be appreciated.

1 Answer 1

4

You can use the filter and sort function . By default array will be sorted comparing the items as strings. So with numbers you need to explicitly pass the sorting function.

.sort((a,b) => a - b);

For strings, the default comparing is good.

var arr = [30, "Chad", 400, 700, "Brian", "Zander", "allen", 43, 50]

var numbers = arr.filter(item => typeof item === 'number').sort((a,b) => a - b);
var strings = arr.filter(item => typeof item === 'string').sort((a,b) => a.localeCompare(b));

console.log(numbers);
console.log(strings);

Sign up to request clarification or add additional context in comments.

4 Comments

What if one of the string names is lower case? Like "allen" instead of "Allen." Suggestion?
@My-name-is-mud by default the Uppercase is coming the first
@My-name-is-mud but you can pass a function for the strings too and use the localeCompare function
Can you give me the syntax for that? Thank you so much.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.