简体   繁体   中英

Sort JavaScript Array With Both Strings and Numbers into a numbers only array and a string only array

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.

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM