对数字数组进行排序,以使空值排在最后

编程入门 行业动态 更新时间:2024-10-23 21:30:29
本文介绍了对数字数组进行排序,以使空值排在最后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个像这样的数组:

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)

更多推荐

对数字数组进行排序,以使空值排在最后

本文发布于:2023-10-14 11:59:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1491000.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   排在   数字   使空值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!