Files
30-seconds-of-code/snippets/array-sample.md
2017-12-15 13:45:12 +05:30

9 lines
299 B
Markdown

### Array sample
Use `Math.random()` to generate a random number, multiply it with `Array.length` and round it of to the nearest whole number using `Math.floor()`. Works with strings too.
```js
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
// sample([3, 7, 9, 11]) -> 9
```