如何对JS数组进行排序,该数组将单词放在前面,将数字放在后面



假设我有这个数组:

[ '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)])

最新更新