Function to choose elements randomly in JavaScript


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.

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

The output in the console will be −

[ 5, 2, 4, 78 ]

Updated on: 21-Oct-2020

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements