Added array shuffle
This commit is contained in:
14
README.md
14
README.md
@ -43,6 +43,7 @@
|
|||||||
* [Reverse a string](#reverse-a-string)
|
* [Reverse a string](#reverse-a-string)
|
||||||
* [RGB to hexadecimal](#rgb-to-hexadecimal)
|
* [RGB to hexadecimal](#rgb-to-hexadecimal)
|
||||||
* [Scroll to top](#scroll-to-top)
|
* [Scroll to top](#scroll-to-top)
|
||||||
|
* [Shuffle array values](#shuffle-array-values)
|
||||||
* [Similarity between arrays](#similarity-between-arrays)
|
* [Similarity between arrays](#similarity-between-arrays)
|
||||||
* [Sort characters in string (alphabetical)](#sort-characters-in-string-alphabetical)
|
* [Sort characters in string (alphabetical)](#sort-characters-in-string-alphabetical)
|
||||||
* [Sum of array of numbers](#sum-of-array-of-numbers)
|
* [Sum of array of numbers](#sum-of-array-of-numbers)
|
||||||
@ -423,6 +424,19 @@ const scrollToTop = _ => {
|
|||||||
// scrollToTop()
|
// scrollToTop()
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### 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]
|
||||||
|
```
|
||||||
|
|
||||||
### Similarity between arrays
|
### Similarity between arrays
|
||||||
|
|
||||||
Use `filter()` to remove values that are not part of `values`, determined using `includes()`.
|
Use `filter()` to remove values that are not part of `values`, determined using `includes()`.
|
||||||
|
|||||||
12
snippets/shuffle-array-values.md
Normal file
12
snippets/shuffle-array-values.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
### 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]
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user