The Codesee
The Codesee

Reputation: 3783

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

Upvotes: 7

Views: 10147

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

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

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122037

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)

Upvotes: 5

Related Questions