diff --git a/README.md b/README.md index dd66eebff..efc81a9de 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ * [RGB to hexadecimal](#rgb-to-hexadecimal) * [Run promises in series](#run-promises-in-series) * [Scroll to top](#scroll-to-top) -* [Shuffle array values](#shuffle-array-values) +* [Shuffle array](#shuffle-array) * [Similarity between arrays](#similarity-between-arrays) * [Sleep](#sleep) * [Sort characters in string (alphabetical)](#sort-characters-in-string-alphabetical) @@ -662,10 +662,9 @@ const scrollToTop = _ => { // scrollToTop() ``` -### Shuffle array values +### Shuffle array -Create an array of random values by using `Array.map()` and `Math.random()`. -Use `Array.sort()` to sort the elements of the original array based on the random values. +Use `Array.sort()` to reorder elements, using `Math.random()` in the comparator. ```js const shuffle = arr => { diff --git a/snippets/randomize-order-of-array.md b/snippets/randomize-order-of-array.md deleted file mode 100644 index 456a00607..000000000 --- a/snippets/randomize-order-of-array.md +++ /dev/null @@ -1,8 +0,0 @@ -### Randomize order of array - -Use `Array.sort()` to reorder elements, utilizing `Math.random()` to randomize the sorting. - -```js -const randomizeOrder = arr => arr.sort((a, b) => Math.random() >= 0.5 ? -1 : 1); -// randomizeOrder([1,2,3]) -> [1,3,2] -``` diff --git a/snippets/shuffle-array-values.md b/snippets/shuffle-array-values.md deleted file mode 100644 index ab3698a31..000000000 --- a/snippets/shuffle-array-values.md +++ /dev/null @@ -1,12 +0,0 @@ -### Shuffle array values - -Create an array of random values by using `Array.map()` and `Math.random()`. -Use `Array.sort()` to sort the elements of the original array based on the random values. - -```js -const shuffle = arr => { - let r = arr.map(Math.random); - return arr.sort((a, b) => r[a] - r[b]); -}; -// shuffle([1,2,3]) -> [2, 1, 3] -``` diff --git a/snippets/shuffle-array.md b/snippets/shuffle-array.md new file mode 100644 index 000000000..6266f9ecf --- /dev/null +++ b/snippets/shuffle-array.md @@ -0,0 +1,8 @@ +### Shuffle array + +Use `Array.sort()` to reorder elements, using `Math.random()` in the comparator. + +```js +const shuffle = arr => arr.sort(() => Math.random() - 0.5); +// shuffle([1,2,3]) -> [2,3,1] +```