Exploring ES2018 and ES2019
Please support this book: buy it or donate
(Ad, please don’t block.)

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:

const arr = [
  { key: 'b', value: 1 },
  { key: 'a', value: 2 },
  { key: 'b', value: 3 },
];
arr.sort((x, y) => x.key.localeCompare(y.key, 'en-US'));
assert.deepEqual(arr, [
  { key: 'a', value: 2 },
  { key: 'b', value: 1 },
  { key: 'b', value: 3 },  
]);

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.