Array.push() and unique items

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.

Answer

Yep, it’s a small mistake.

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

Leave a Reply

Your email address will not be published. Required fields are marked *