Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
};
like image 833
The Codesee Avatar asked May 06 '17 11:05

The Codesee


1 Answers

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)
like image 184
Nenad Vracar Avatar answered Sep 21 '22 00:09

Nenad Vracar