0

Given this code:

[1, 2].sort(a => a == 1 ? 1 : 0)

If I run it in Chromium (v75) I get [1, 2]. However, if I run the same code in Firefox (Nightly) I get [2, 1].

Similar differences exist between Node v10 ([2, 1]) and v12 ([1, 2]).

Why is this?

Chris Smith
  • 2,928
  • 4
  • 27
  • 59
  • 2
    The comparison function provided is not consistent, so the output is implementation-defined. A consistent comparison function should have: for two elements being compared `a` and `b`, if `compareFn(a, b) < 0` then also `compareFn(b, a) > 0`, which is not the case here. A return value of 0 for the compare function indicates "these two elements may as well be next to each other when sorted, in any order" (which is contradictory for, when `(b, a)` is checked rather than `(a, b)`, a return value of 1 is supplied, which indicates that one should come before the other) – CertainPerformance Jul 31 '19 at 23:22
  • `sort()` takes *two* arguments, so you're returning `0` for each, as in "don't care about the order" – tadman Jul 31 '19 at 23:23
  • @CertainPerformance Thanks, that answered my question. I suppose a proper implementation would be this: `[1, 2].sort((a, b) => a == 1 ? 1 : (b == 1 ? -1 : 0))` – Chris Smith Jul 31 '19 at 23:33
  • Sure, or to make things easier, just return the difference, eg `(a, b) => a - b` or `(a, b) => b - a` – CertainPerformance Jul 31 '19 at 23:34

0 Answers0