本文介绍了对数字数组进行排序,以使空值排在最后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的数组:
I have an array like this:
var arr = [5, 25, null, 1, null, 30]使用此代码从低到高对数组进行排序,这就是输出所显示的内容:
Using this code to sort the array from low to high, this is what's displayed as the output:
null null 1 5 25 30
null null 1 5 25 30
arr.sort(function (a, b) { return a - b; };
但是,我希望最后显示空值,如下所示:
However, I would like the null values to be displayed last, like this:
1 5 25 30 null null
1 5 25 30 null null
我查看了对数组进行排序空值始终排在最后并尝试了此代码,但是输出仍然与第一个相同-空值排在最前:
I had a look at Sort an array so that null values always come last and tried this code, however the output is still the same as the first - the null values come first:
arr.sort(function (a, b) { return (a===null)-(b===null) || +(a>b)||-(a<b); };推荐答案
您可以先按null而不是数字进行排序.
You can first sort by not null and then by numbers.
var arr = [5, 25, null, 1, null, 30] arr.sort(function(a, b) { return (b != null) - (a != null) || a - b; }) console.log(arr)
更多推荐
对数字数组进行排序,以使空值排在最后
发布评论