Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
How to generate Random numbers, then exclude array of numbers

i would like to generate random numbers from 1-50, then exclude an array like; 4,7,10,20,35 etc

i tried this;

let mainNum = 50
let exclNum = [4, 7, 10, 20, 35];
if (!exclNum.includes(mainNum)) {
  console.log(Math.floor(Math.random() * mainNum) + 1)
}

but it still generates numbers that's still in the array, please is there anything i am missing?

Thanks for your response in advance

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You need to generate the random number first, then check if it's in the array. Do this in a loop until it's not in the array.

let mainNum = 50
let exclNum = [4, 7, 10, 20, 35];
let ranNum;
while (true) {
  ranNum = Math.floor(Math.random() * mainNum) + 1;
  if (!exclNum.includes(ranNum)) {
    break;
  }
}
console.log(ranNum);

about 4 years ago · Juan Pablo Isaza Report

0

You are currently checking whether exclNum includes mainNum, which is 50.

Instead, generate the random number and check whether exclNum includes it:

let mainNum = 50
let exclNum = [4, 7, 10, 20, 35];

while(!exclNum.includes((randomNum = Math.floor(Math.random() * mainNum) + 1))){
  console.log(randomNum)
  break;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

about 4 years ago · Juan Pablo Isaza Report

0

A do... while loop is more concise

function myRandom(mainNum, exclude) {
    let r;
    do {
        r = Math.floor(Math.random() * mainNum) + 1;
    } while(exclude.includes(r))
    return r;
}

console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!