diff --git a/snippets/stableSort.md b/snippets/stableSort.md index b14535e73..5a37fb1d6 100644 --- a/snippets/stableSort.md +++ b/snippets/stableSort.md @@ -1,9 +1,11 @@ ### stableSort -Performs stable sort. Useful in Chrome and NodeJS. +Performs stable sorting of an array, preserving the initial indexes of items when their values are the same. +Does not mutate the original array, but returns a new array instead. -Use `Array.map()` to pair each element of the input array with its corresponding index. Then use `Array.sort()` and a user provided `compare()` function. If the items are equal, sort them by their initial index in the input array. Lastly use `Array.map()` to convert back to the initial array items. -Returns new array without modifying the initial one. +Use `Array.map()` to pair each element of the input array with its corresponding index. +Use `Array.sort()` and a `compare` function to sort the list, preserving their initial order if the items compared are equal. +Use `Array.map()` to convert back to the initial array items. ```js const stableSort = (arr, compare) => @@ -16,5 +18,4 @@ const stableSort = (arr, compare) => ```js const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const stable = stableSort(arr, () => 0); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] -const unstable = [...arr].sort(() => 0); // [5, 0, 2, 3, 4, 1, 6, 7, 8, 9, 10] (in Chrome/NodeJS) ```