How to exclude certain values from randomly generated array JavaScript

We need to create a function that generates an array of random numbers while excluding certain values. The function takes two arguments: the desired array length and an array of numbers to exclude.

Requirements:

  • Generate random numbers between 0 and 100
  • Exclude numbers present in the exclusion array
  • No duplicate numbers in the result

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));
[
  23, 93, 29, 25, 37,
  63, 54, 11, 69, 79
]

How It Works

The function uses a loop that continues until we have the required number of elements:

  1. Math.floor(Math.random() * 100) generates random integers from 0-99
  2. !absentArray.includes(random) checks the number isn't in the exclusion list
  3. !randomArray.includes(random) ensures no duplicates in the result
  4. Only qualifying numbers are added to the result array

Improved Version with Set

Using a Set improves performance for duplicate checking:

const generateRandomOptimized = (len, absentArray) => {
    const absentSet = new Set(absentArray);
    const resultSet = new Set();
    
    while(resultSet.size < len) {
        const random = Math.floor(Math.random() * 100);
        if(!absentSet.has(random)) {
            resultSet.add(random);
        }
    }
    
    return Array.from(resultSet);
}

console.log(generateRandomOptimized(8, [10, 20, 30, 40, 50]));
[ 15, 67, 92, 3, 84, 71, 36, 88 ]

Key Points

  • Set approach: More efficient for large exclusion lists
  • Loop condition: Continue until we have enough valid numbers
  • Range: Adjust Math.random() * 100 for different ranges

Conclusion

This approach efficiently generates random arrays while excluding specific values. The Set-based version offers better performance for larger datasets by eliminating the need for repeated array searches.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements