Please support this book: buy it or donate

18. Stable Array.prototype.sort()

Starting with ECMAScript 2019, the Array method .sort() is guaranteed to be stable. What does that mean (as proposed by Mathias Bynens)?

It means that if elements that are considered equal by sorting (not necessarily in any other way!) then sorting does not change the order of those elements. For example:

  1. const arr = [
  2. { key: 'b', value: 1 },
  3. { key: 'a', value: 2 },
  4. { key: 'b', value: 3 },
  5. ];
  6. arr.sort((x, y) => x.key.localeCompare(y.key, 'en-US'));
  7. assert.deepEqual(arr, [
  8. { key: 'a', value: 2 },
  9. { key: 'b', value: 1 },
  10. { key: 'b', value: 3 },
  11. ]);

Two objects have the same .key, 'b'. Their order will always be preserved by .sort(). One benefit is that a unit test where stability matters, now works the same across engines.