Array.push() and unique items

后端 未结 12 490
梦谈多话
梦谈多话 2020-12-24 10:45

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


        
相关标签:
12条回答
  • 2020-12-24 10:50

    Your logic is saying, "if this item exists already, then add it." It should be the opposite of that.

    Change it to...

    if (this.items.indexOf(item) == -1) {
        this.items.push(item);
    }
    
    0 讨论(0)
  • 2020-12-24 10:51

    You have to use === -1, if it equals to -1 i.e. item is not available in your array:

      this.items = [];
    
      add(item) {
        if(this.items.indexOf(item) === -1) {
          this.items.push(item);
          console.log(this.items);
        }
      }
    
    0 讨论(0)
  • 2020-12-24 10:51

    Push always unique value in array

    ab = [
         {"id":"1","val":"value1"},
         {"id":"2","val":"value2"},
         {"id":"3","val":"value3"}
       ];
    
    
    
    var clickId = [];
    var list = JSON.parse(ab);
    $.each(list, function(index, value){
        if(clickId.indexOf(value.id) < 0){
            clickId.push(value.id);
        }
    });
    
    0 讨论(0)
  • 2020-12-24 10:53

    I guess ES6 has set data structure, which you can use for unique entries

    0 讨论(0)
  • 2020-12-24 10:56

    In case if you are looking for one liner

    For primitives

    this.items.indexOf(item) === -1) && this.items.push(item);
    

    For objects

    this.items.findIndex((item: ItemType) => item.var === checkValue) === -1 && this.items.push(item);
    
    0 讨论(0)
  • 2020-12-24 11:01
    var helper = {};
    for(var i = 0; i < data.length; i++){
      helper[data[i]] = 1; // Fill object
    }
    var result = Object.keys(helper); // Unique items
    
    0 讨论(0)
提交回复
热议问题