random index javascript code example
Example 1: get random element from array js
var item = items[Math.floor(Math.random() * items.length)];
Example 2: get random entry from array javascript
const rnd = (arr) => { return arr[Math.floor(Math.random() * arr.length)] };
Example 3: get random item from array javascript
let items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
let randomItem = items[Math.floor(Math.random() * items.length)];
Example 4: get random elements from array javascript
array.sort(() => Math.random() - Math.random()).slice(0, n)
Example 5: get random elements from array javascript
const arr = myArray
.map((a) => ({sort: Math.random(), value: a}))
.sort((a, b) => a.sort - b.sort)
.map((a) => a.value)