Seems very basic but I can't find any info on why is it happening.
I'm using the canonical MDN example to sort an array of objects and it seems the order in which the elements are passed into the compare callback is the opposite order. e.g.
let items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'And', value: 45 },
{ name: 'The', value: -12 },
{ name: 'Magnetic', value: 13 },
{ name: 'Zeros', value: 37 }
];
// sort by value
items.sort(function (a, b) {
console.log(a.name, b.name);
return -1; // should keep the original order
});
// getting
// Sharpe Edward
// And Sharpe
// The And
// Magnetic The
// Zeros Magnetic
Again documentation says:
If compareFunction(a, b) returns less than 0, leave a and b unchanged.
What am I missing?
awill be some value andbanother, but the comparator may be called again with the values swapped. The return value must be consistent. Also, -1 does not mean "leave values in current order", is is an explicit indication that the first value (a) should go before the second (b).compareFunction(a, b)returns less than 0, sortato an index lower thanb" That is much more clearer and consistent with the greater than 0 part.