I have this array of objects with an n
and an o
property holding an integer.
And I want to sort it by ascending value of the n
property, and if two elements have the same value of n
, then I want to order them by ascending value of o
.
I know that the right way of doing this would be:
const s = [
{ n: 0, o: 0 },
{ n: 2, o: 1 },
{ n: 3, o: 2 },
{ n: 7, o: 3 },
{ n: 4, o: 4 },
{ n: 8, o: 5 },
{ n: 2, o: 6 },
{ n: 0, o: 7 },
{ n: 3, o: 8 },
{ n: 4, o: 9 },
{ n: 8, o: 10 },
{ n: 7, o: 11 },
{ n: 3, o: 12 },
{ n: 3, o: 13 },
];
console.log(s.sort((a, b) => (a.n === b.n ? a.o - b.o : a.n - b.n)));
But since o
is basically the index of an object in the array, I thought I could swap a.o - b.o
with -1
, that is: if a.n === b.n
, then "sort a
before b
", meaning preserve the order between a
and b
.
But it tuns out that -1
would actually sort by descending value of o
:
const s = [
{ n: 0, o: 0 },
{ n: 2, o: 1 },
{ n: 3, o: 2 },
{ n: 7, o: 3 },
{ n: 4, o: 4 },
{ n: 8, o: 5 },
{ n: 2, o: 6 },
{ n: 0, o: 7 },
{ n: 3, o: 8 },
{ n: 4, o: 9 },
{ n: 8, o: 10 },
{ n: 7, o: 11 },
{ n: 3, o: 12 },
{ n: 3, o: 13 },
];
console.log(s.sort((a, b) => (a.n === b.n ? -1 : a.n - b.n)));
While if I try 1
rather than -1
I get the sorting I wanted.
Why do I need to return a positive value to keep the order of the elements, when the docs say the opposite? And can I rely on this behaviour or do I have to return a.o - b.o
instead of 1
to consistently get the order I want?