I'm facing with a sorting problem in javascript. I wrote a simple sorting function where I want the null elements on top:
This is the function:
var mySort = function(a, b) {
if (!a && !b) return 0;
if (!a) return -1;
if (!b) return -1;
if (a > b) return 1;
if (a < b) return -1;
return 0;
}
Let's take the following array as example:
var array = [1, 9, 4, 8, null, 2, 3, 4, null, 6, 3, 2, 8, 9, 5];
By calling array.sort(mySort) the non null values are always sorted, but the null values position alternate from the beginning and the end of the array:
Odd calls: [null, null, 1, 2, 2, 3, 3, 4, 4, 5, 6, 8, 8, 9, 9]
Even calls: [1, 2, 2, 3, 3, 4, 4, 5, 6, 8, 8, 9, 9, null, null]
Why?
Edit:
In a comment HMR head me to an error in the algorithm: if (!b) return -1; should be if (!b) return 1;. Now it works fine with stings and numbers.
array.slice().sort(mySort)if one item is falsy (null) it's either put on the start or the end but if they're both null then none of the items are moved. So the nulls will group at the start or the end. If you doif (!b) return 1;then it'll also always be the same.slice) or return a different value when one is null.if (!b) return -1;is wrong, it should beif (!b) return 1;Now it works fine!.Thanks!nullor'null'as string in the array?