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.

>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)

Leave a Reply