DevAra
DevAra

Reputation: 530

create unique value and push to array in javascript

I need to create a array with unique values. In here if the created value is include in that array, then need to create another value and again need to check that newly created value exists in that array, if again exists then need to do the same check.

Here is the code I have tried, if I execute this, I think infinite looping scene happening.

let arr = [];
for(let i=0; i<10;i++) {
  let k = 1;
  let pass = (Math.floor(Math.random() * (10 - 6 + 1)) + 6)+'a';
  while(k > 0){
    k++;
    if(arr.indexOf(pass) > -1) {
      pass = (Math.floor(Math.random() * (10 - 6 + 1)) + 6)+'a';
    } else {
      arr.push(pass);
      break;         
    }
   
    console.log(arr)
  }
}

What was the mistake in this code?

Upvotes: 0

Views: 40

Answers (2)

Alaksandar Jesus Gene
Alaksandar Jesus Gene

Reputation: 6887

let arr = [(Math.floor(Math.random() * (10)))+'a'];
 for(let i=0; i<=10;i++) {
   let k = 0;
    let pass = (Math.floor(Math.random() * (10)))+'a';
   while(k < arr.length){
       k++;
        if(arr.indexOf(pass) > -1){
            pass = (Math.floor(Math.random() * (10 - 6 + 1)) + 6)+'a';
        }else {
            arr.push(pass);
            break;
         }
        
  
     }


    }
    
    
    console.log(arr)

variable k is always > 0 in your condition and it loops infinitely.

edit 1:

answer updated based on @Mathew answer

Upvotes: 0

Mathew Alden
Mathew Alden

Reputation: 1670

Yep, you're correct. It's an infinite loop.

The problem is the line pass = (Math.floor(Math.random() * (10 - 6 + 1)) + 6)+'a';. This will only ever generate one of 5 values. pass will only ever be

  • 6a
  • 7a
  • 8a
  • 9a
  • 10a

Beause your array is 10 elements long, but you're only filling it with 5 possible elements, you will never be able to fill it with all unique elements. So it will go into an infinite loop trying to generate unique elements but never finding unique elements.

You need to rewrite the calculation of pass to generate more than 5 unique elements. Try pass = (Math.floor(Math.random() * 10))+'a'; and go from there.

Upvotes: 2

Related Questions