ECMAScript question detail
Array Stable Sort
The sort method for arrays is stable in ES2020. i.e, If you have an array of objects and sort them on a given key, the elements in the list will retain their position relative to the other objects with the same key.
Now the array is using the stable TimSort algorithm for arrays over 10 elements instead of the unstable QuickSort.
Let's see an example of users retain their original position with same age group.
const users = [
{ name: "Albert", age: 30 },
{ name: "Bravo", age: 30 },
{ name: "Colin", age: 30 },
{ name: "Rock", age: 50 },
{ name: "Sunny", age: 50 },
{ name: "Talor", age: 50 },
{ name: "John", age: 25 },
{ name: "Kindo", age: 25 },
{ name: "Lary", age: 25 },
{ name: "Minjie", age: 25 },
{ name: "Nova", age: 25 }
]
users.sort((a, b) => a.age - b.age);