Reputation: 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.
Upvotes: 0
Views: 82
Reputation: 68655
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);
Upvotes: 3