Problem
Let's make a basic list and sort it to make sure that 2 is ALWAYS first in the list. Simple enough, right?
[1, 2, 3].sort((a, b) => {
if (a === 2) return -1;
return 0;
});
Chrome result: ✓
[2, 1, 3]
Node result: X
[1, 2, 3]
In order to get this behaviour in Node, you could - weirdly enough - look at the b parameter and make it return 1 if it's 2:
[1, 2, 3].sort((a, b) => {
if (b === 2) return 1;
return 0;
});
With this implementation you get the opposite result; Chrome will be [1, 2, 3] and Node will be [2, 1, 3].
Questions
Do you have a logical explaination for this behaviour? Is my sorting function conceptually flawed? If so, how would you write this sorting behaviour?
[1,2,3]if (a === 2) return -1; if (b === 2) return 1;to the compareFunction. If you add aconsole.log(a,b)inside the function, you should see different logs for chrome and node0, or a value< 0or> 0. Your comparison incorrectly declares values equal that aren't equal, so the outcome is random for all intents and purposes. There's also no reason whyaorbspecifically can be expected to be2..sort()callback must be consistent: the result forcompare(a, b)andcompare(b, a)have to make sense.compareFunction(a, b)must always return the same value when given a specific pair of elementsaandbas its two arguments. If inconsistent results are returned, then the sort order is undefined."