How to get a number of random elements from an array?

Shyam Dixit picture Shyam Dixit · Oct 9, 2013 · Viewed 77.9k times · Source

I am working on 'how to access elements randomly from an array in javascript'. I found many links regarding this. Like: Get random item from JavaScript array

var item = items[Math.floor(Math.random()*items.length)];

But in this, we can choose only one item from the array. If we want more than one elements then how can we achieve this? How can we get more than one element from an array?

Answer

Abdennour TOUMI picture Abdennour TOUMI · Jul 25, 2016

Just two lines :

// Shuffle array
const shuffled = array.sort(() => 0.5 - Math.random());

// Get sub-array of first n elements after shuffled
let selected = shuffled.slice(0, n);

DEMO: