Merge pull request #88 from darrenscerri/shuffle
This commit is contained in:
@ -63,7 +63,7 @@
|
|||||||
* [RGB to hexadecimal](#rgb-to-hexadecimal)
|
* [RGB to hexadecimal](#rgb-to-hexadecimal)
|
||||||
* [Run promises in series](#run-promises-in-series)
|
* [Run promises in series](#run-promises-in-series)
|
||||||
* [Scroll to top](#scroll-to-top)
|
* [Scroll to top](#scroll-to-top)
|
||||||
* [Shuffle array values](#shuffle-array-values)
|
* [Shuffle array](#shuffle-array)
|
||||||
* [Similarity between arrays](#similarity-between-arrays)
|
* [Similarity between arrays](#similarity-between-arrays)
|
||||||
* [Sleep](#sleep)
|
* [Sleep](#sleep)
|
||||||
* [Sort characters in string (alphabetical)](#sort-characters-in-string-alphabetical)
|
* [Sort characters in string (alphabetical)](#sort-characters-in-string-alphabetical)
|
||||||
@ -662,10 +662,9 @@ const scrollToTop = _ => {
|
|||||||
// scrollToTop()
|
// scrollToTop()
|
||||||
```
|
```
|
||||||
|
|
||||||
### Shuffle array values
|
### Shuffle array
|
||||||
|
|
||||||
Create an array of random values by using `Array.map()` and `Math.random()`.
|
Use `Array.sort()` to reorder elements, using `Math.random()` in the comparator.
|
||||||
Use `Array.sort()` to sort the elements of the original array based on the random values.
|
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const shuffle = arr => {
|
const shuffle = arr => {
|
||||||
|
|||||||
@ -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]
|
|
||||||
```
|
|
||||||
@ -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]
|
|
||||||
```
|
|
||||||
8
snippets/shuffle-array.md
Normal file
8
snippets/shuffle-array.md
Normal file
@ -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]
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user