Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.push() and unique items

Tags:

javascript

I have a simple case of pushing unique values into array. It looks like this:

  this.items = [];    add(item) {     if(this.items.indexOf(item) > -1) {       this.items.push(item);       console.log(this.items);     }   } 

Seems pretty straight-forward, right? No, as it appears. It doesn't add any values. I am sure it's some kind of silly mistake on my side, but I can't seem to find it.

like image 926
Tomek Buszewski Avatar asked Apr 19 '16 13:04

Tomek Buszewski


People also ask

What does push () method of the array do?

push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array. Parameters This method contains as many numbers of parameters as the number of elements to be inserted into the array.

How do you find unique elements in an array?

Step 1 − Declare an array and input the array elements at run time. Step 2 − Start traversing the array and check, if the current element is already present in an array or not. Step 3 − If it is already present in an array then, move to the next element in an array and continue.


1 Answers

Yep, it's a small mistake.

if(this.items.indexOf(item) === -1) {     this.items.push(item);     console.log(this.items); } 
like image 192
Jagdish Idhate Avatar answered Oct 10 '22 23:10

Jagdish Idhate