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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With