Merge pull request #88 from darrenscerri/shuffle

This commit is contained in:
Angelos Chalaris
2017-12-14 11:10:47 +02:00
parent 3b0fa08fdd
commit f8d55631c6
4 changed files with 11 additions and 24 deletions

View File

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

View File

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

View 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]
```