Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why not unique numbers are still coming?

I need to generate the unique numbers, join it with the letter and push to array.

arr = []
for (var i = 0; i < 5; i++) {
  function generateRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
  }
  var randomNum = generateRandomNumber(1, 15);
  if (!arr.includes(randomNum)) {
    arr.push('B' + randomNum.toString())
  } else {
    if (arr.length < 5) {
      return generateRandomNumber(min, max)
    } else break
  }
}

I have provisioned uniqueness check, however the same values are still coming.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Condition only checked once in the loop.
Also if the condition is in the else state, there is a chance that there will also be same number as previous.
You can use this approach

let arr = []
function generateRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

function add(){
  var randomNum = generateRandomNumber(1, 15);
    if(arr.length < 5){
        if (!arr.includes('B' + randomNum.toString())) {
            arr.push('B' + randomNum.toString())
        }
        add()
    }
  
}
add()
console.log(arr)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading