0

What I'd expect with the next snippet to leave everything at it's index, but sort a specific item to the front:

const sorted = ["AUS", "GBR", "GER", "USA", "ZAF"].sort(code => code === "GBR" ? -1 : 0);

console.log(sorted);

Where I use just the first element, as I don't compare, just take care about if the first element is GBR, place it to the front, otherwise, let it stay where it is now.

It works well on Chrome, but somehow Firefox leaves everything how it was originally. Or if I do ? -1 : 1, it places GBR to the front, but reverses the order of the rest of the items.

What am I doing wrong?

Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64
  • 6
    The `sort` callback must take two arguments. You're only ever looking at the first argument. If `"GBR"` is passed as the second parameter, it's never examined and the result is random for all intents and purposes. – deceze Sep 24 '19 at 09:19
  • 1
    Also note that the sort algorithm [might not be stable in older implementations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Browser_compatibility). – str Sep 24 '19 at 09:22
  • Perhaps the confusion comes because you were thinking that the custom sort function was meant to assign a final index or position to individual elements but in fact it compares pairs of elements. – Álvaro González Sep 24 '19 at 09:24
  • 1
    I think the relevant quote from the spec is [`If comparefn is not undefined and is not a consistent comparison function for the elements of this array (see below), the sort order is implementation-defined.`](https://tc39.es/ecma262/#sec-array.prototype.sort) – ASDFGerte Sep 24 '19 at 09:24

1 Answers1

1

as deceze said in comments : The sort callback must take two arguments. You're only ever looking at the first argument. If "GBR" is passed as the second parameter, it's never examined and the result is random for all intents and purposes.

you just need to take a look at the second argument :

const sorted = ["AUS", "GBR", "GER", "USA", "ZAF"].sort((c1, c2) => c1 === "GBR" ? -1 : c2 === "GBR" ? 1 : 0);

console.log(sorted);
jonatjano
  • 3,576
  • 1
  • 15
  • 20