Sort stability
A property of a sort that ensures sorting by one method will preserve the order of values that are sorted to the same spot.
JavaScript's sort has sort stability.
const party = [
{ name: 'ditto', level: 12 },
{ name: 'charmander', level: 8 },
{ name: 'bulbasaur', level: 8 },
{ name: 'abra', level: 12 }
];
party.sort(
(a, b) => a.name.localeCompare(b.name));
// sorted by name
[
{ name: 'abra', level: 12 },
{ name: 'bulbasaur', level: 8 },
{ name: 'charmander', level: 8 },
{ name: 'ditto', level: 12 }
]
party.sort((a, b) => a.level - b.level);
// name order is preserved for values
// with equal level
// sorted by level then name
[
{ name: 'bulbasaur', level: 8 },
{ name: 'charmander', level: 8 },
{ name: 'abra', level: 12 },
{ name: 'ditto', level: 12 }
]