简体   繁体   English

在javascript中对数字和null进行排序的数组

[英]sort array of numbers and nulls in javascript

I need some help to write sorting function for DataTables. 我需要一些帮助来编写DataTables的排序功能。 I have a column that contains currency - numbers with positive and negative values as well as blanks. 我有一列包含货币-具有正负值的数字以及空格。
I would like to have the nulls appear as last (/first) but they always come before the negative values. 我想让空值显示为最后(/ first),但它们总是出现在负值之前。 Could anybody hint me towards the solution? 有人可以向我暗示解决方案吗?

提示是排序时将空值更改为Number.NEGATIVE_INFINITY或Number.POSITIVE_INFINITY

Given an array of numbers which also contains null , if you want to sort them and keep null at the end of the results, you can customize your sort function this way: 给定一个也包含null的数字数组,如果要对它们排序并在结果末尾保留null ,则可以通过以下方式自定义排序函数:

var num = [-22,55,30,0,0,null,350,null,10000,-20];

num.sort(function(a,b){
    if (b == null) return -1;
    else if (a==null) return 1;
    else return a > b
});

// [-22, -20, 0, 0, 30, 55, 350, 10000, null, null]

This example above treats null as the largest number so when sort the array, nulls come last (see the sort function). 上面的示例将null视为最大数字,因此对数组进行排序时,null排在最后(请参阅sort函数)。 If you want the reverse order, you can make a modification to that customized sort function. 如果需要相反的顺序,则可以对该自定义排序功能进行修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM