7

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);
};
The Codesee
  • 3,714
  • 5
  • 38
  • 78

2 Answers2

5

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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • How would you do it so that the array looks like [30, 25, 5, 1, null, null] ...? – razorsyntax Oct 20 '18 at 16:37
  • 1
    @razorsyntax `arr.sort((a, b) => (b != null) - (a != null) || b - a)` – Nenad Vracar Oct 20 '18 at 16:39
  • @NenadVracar how do you do it if you want to place null first?? – Abhishek Ekaanth Sep 25 '20 at 07:07
  • @NenadVracar Can you explain what is happening in the first part of the return? Struggling to understand what it's doing exactly – Thomas Allen Mar 10 '21 at 16:37
  • 1
    @ThomasAllen If the a is null and b is not null then the result of the first part of the expression will be 1 because bacause `(b != null) - (a != null) = true - false = 1 - 0 = 1` and when a is not null and b is null then the result will be -1. If both a and b are not null then the result of first condition is 0 because `false - false = 0 - 0 = 0` and then the second part of the expression is called, after || and that is just `a - b` – Nenad Vracar Mar 10 '21 at 17:00
  • 1
    @AbhishekEkaanth You would just switch a and b in the first part of return expression like so https://jsfiddle.net/812y4j5c/1/ – Nenad Vracar Mar 10 '21 at 17:03
  • @NenadVracar I was able to get it working. Thanks :)) – Abhishek Ekaanth Mar 15 '21 at 11:07
1

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392