对数字数组进行排序,以使空值排在最后 [英] Sort an array of numbers so that null values come last

查看:152
本文介绍了对数字数组进行排序,以使空值排在最后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组:

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)

这篇关于对数字数组进行排序,以使空值排在最后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆