Sort an array of numbers so that the null values ​​are the last

I have an array like this:

var arr = [5, 25, null, 1, null, 30]

Using this code to sort an array from low to high is what appears as the result:

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, for example:

1 5 25 30 null null

I looked at Sort Array so that null values ​​always come last and try this code, however, the output is the same as the first - null values ​​will be first:

arr.sort(function (a, b) {
        return (a===null)-(b===null) || +(a>b)||-(a<b);
};
+4
source share
2 answers

You can sort first, and not null, 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)
Run code
+1

null, , a b .

, numberfor, null.

var array = [5, 25, null, 1, null, 30];

array.sort(function(a, b) {
    return (a === null) - (b === null) || a - b;
});

console.log(array);
0

Source: https://habr.com/ru/post/1676544/


All Articles