繁体   English   中英

JS数组如何排序,前面的单词和原数组的顺序一样,后面的数字排序

[英]How to sort JS array that puts the words in front in the same order as the original array and the numbers sorted in the back

说我有这个数组:

[ 'say', 'burger', '2000', '1000', '3000', 'full', 'no' ]

我希望结果如下:

['say', 'burger', 'full', 'no', '1000', '2000', '3000']

请注意,单词都在前面,但与原始数组的顺序相同,后面的数字已排序。 我该怎么做呢?

您可以检查NaN并将此字符串移至顶部。

 var array = ['say', 'burger', '2000', '1000', '3000', 'full', 'no']; array.sort((a, b) => isNaN(b) - isNaN(a) || a - b); console.log(array);

 const arr = ['say', 'burger', '2000', '1000', '3000', 'full', '300', 'no'] //['say', 'burger', 'full', 'no', '1000', '2000','300','3000'] const stringArr = []; const intArr = [] arr.map(el => { if (!isNaN(el)) intArr.push(el); else stringArr.push(el) }) console.log([...stringArr, ...intArr.sort((a, b) => a - b)])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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