简体   繁体   中英

Sort an array of numbers so that null values come last

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

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

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);
};

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) 

I would use a strict comparison with null , because any type casting is omitted and you need for the second part only the delta of a and b for sorting.

The given example works for objects with null value or with some properties, like the given key numberfor , which is not available here in the array of null values and numbers.

 var array = [5, 25, null, 1, null, 30]; array.sort(function(a, b) { return (a === null) - (b === null) || a - b; }); console.log(array); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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