试图从一个只包含整数的数组中获得最大值和最小值似乎比我想象的要难。
var numArray = [140000, 104, 99]; numArray = numArray.sort(); console.log(numArray)
我希望这是99 104 140000。相反,它显示的是104、14万、99。看起来排序是把值当做字符串处理的。
有没有办法让排序函数对整数值进行排序?
试图从一个只包含整数的数组中获得最大值和最小值似乎比我想象的要难。
var numArray = [140000, 104, 99]; numArray = numArray.sort(); console.log(numArray)
我希望这是99 104 140000。相反,它显示的是104、14万、99。看起来排序是把值当做字符串处理的。
有没有办法让排序函数对整数值进行排序?
当前回答
sort_mixed
Object.defineProperty(Array.prototype,"sort_mixed",{
value: function () { // do not use arrow function
var N = [], L = [];
this.forEach(e => {
Number.isFinite(e) ? N.push(e) : L.push(e);
});
N.sort((a, b) => a - b);
L.sort();
[...N, ...L].forEach((v, i) => this[i] = v);
return this;
})
try a =[1,'u',"V",10,4,"c"," a "].sort_mixed();console.log (a)
其他回答
sort_mixed
Object.defineProperty(Array.prototype,"sort_mixed",{
value: function () { // do not use arrow function
var N = [], L = [];
this.forEach(e => {
Number.isFinite(e) ? N.push(e) : L.push(e);
});
N.sort((a, b) => a - b);
L.sort();
[...N, ...L].forEach((v, i) => this[i] = v);
return this;
})
try a =[1,'u',"V",10,4,"c"," a "].sort_mixed();console.log (a)
当数组只包含没有无穷大或NaN的数字时,接受的答案和类似numArray.sort((a,b) => a - b)的等价物是很好的。它们可以被扩展到处理无穷大和NaN,如下所示:
numArray.sort((a,b) => (+a || 0) - (+b || 0) || 0);
这将NaN(或任何非数字,如'foo'或{})排序为0。最后的|| 0需要处理a和b等于无穷大的情况。
默认情况下,sort方法按字母顺序对元素排序。要进行数字排序,只需添加一个处理数字排序的新方法(sortNumber,如下所示)
var numArray = [140000, 104, 99]; numArray.sort(function(a, b) { 返回 A - B; }); console.log(numArray);
文档:
Mozilla Array.prototype.sort()建议对不包含Infinity或NaN的数组使用这个比较函数。(因为∞-∞是NaN,不是0)。
还有按键排序对象的例子。
我同意aks,但是不用
return a - b;
你应该使用
return a > b ? 1 : a < b ? -1 : 0;
处理undefined, null和NaN: null的行为像0,NaN和undefined结束。
array = [3, 5, -1, 1, NaN, 6, undefined, 2, null]
array.sort((a,b) => isNaN(a) || a-b)
// [-1, null, 1, 2, 3, 5, 6, NaN, undefined]