Merge pull request #88 from darrenscerri/shuffle
This commit is contained in:
@ -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