Update stableSort.md
This commit is contained in:
@ -1,9 +1,11 @@
|
|||||||
### stableSort
|
### 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.
|
Use `Array.map()` to pair each element of the input array with its corresponding index.
|
||||||
Returns new array without modifying the initial one.
|
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
|
```js
|
||||||
const stableSort = (arr, compare) =>
|
const stableSort = (arr, compare) =>
|
||||||
@ -16,5 +18,4 @@ const stableSort = (arr, compare) =>
|
|||||||
```js
|
```js
|
||||||
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
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 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)
|
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user