JavaScript - How to pick random elements from an array?


Suppose, we have an array of literals that contains no duplicate elements like this −

const arr = [2, 5, 4, 45, 32, 46, 78, 87, 98, 56, 23, 12];

We are required to write a JavaScript function that takes in an array of unique literals and a number n.

The function should return an array of n elements all chosen randomly from the input array and no element should appear more than once in the output array.

Example

Following is the code −

const arr = [2, 5, 4, 45, 32, 46, 78, 87, 98, 56, 23, 12];
const chooseRandom = (arr, num = 1) => {
   const res = [];
   for(let i = 0; i < num; ){
      const random = Math.floor(Math.random() * arr.length);
      if(res.indexOf(arr[random]) !== -1){
         continue;
      };
      res.push(arr[random]);
      i++;
   };
   return res;
};
console.log(chooseRandom(arr, 4));

Output

This will produce the following output in console −

[ 5, 2, 4, 78 ]

Updated on: 30-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements