Update stableSort.md

This commit is contained in:
Angelos Chalaris
2018-02-18 19:41:43 +02:00
committed by GitHub
parent 8b7dd96474
commit cf23cdd1b7

View File

@ -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)
```