How to exclude certain values from randomly generated array JavaScript


We have to create a function that takes in 2 arguments: an integer and an array of integers. First argument denotes the length of array we have to return and the second argument contains the elements that should not be present in our return array. Actually, we need an array of random numbers between 0 to 100 but it should not include any element that’s present in the argument array.

Note − No two numbers should be duplicate.

Let’s call our function generateRandom(). The code for this would be −

Example

const absentArray = [44, 65, 5, 34, 87, 42, 8, 76, 21, 33];
const len = 10;
const generateRandom = (len, absentArray) => {
   const randomArray = [];
   for(let i = 0; i < len; ){
      const random = Math.floor(Math.random() * 100);
   if(!absentArray.includes(random) &&
      !randomArray.includes(random)){
         randomArray.push(random);
         i++;
      }
   };
   return randomArray;
}
console.log(generateRandom(len, absentArray));

Output

Output in the console will be −

[
   23, 93, 29, 25, 37,
   63, 54, 11, 69, 79
]

Updated on: 19-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements