Array.push() and unique items

后端 未结 12 488
梦谈多话
梦谈多话 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 11:01

    Using Set

    this.items = new Set();
    this.items.add(1);
    this.items.add(2);
    this.items.add(1);
    this.items.add(2);
    
    console.log(Array.from(this.items)); // [1, 2]
    
    0 讨论(0)
  • 2020-12-24 11:03

    You can use the Set structure from ES6 to make your code faster and more readable:

    // Create Set
    this.items = new Set();
    
    add(item) {
        this.items.add(item);
    
        // Set to array
        console.log([...this.items]);
    }
    
    0 讨论(0)
  • 2020-12-24 11:06

    try .includes()

    [1, 2, 3].includes(2);     // true
    [1, 2, 3].includes(4);     // false
    [1, 2, 3].includes(3, 3);  // false
    [1, 2, 3].includes(3, -1); // true
    [1, 2, NaN].includes(NaN); // true
    

    so something like

    const array = [1, 3];
    if (!array.includes(2))
        array.push(2);
    

    note the browser compatibility at the bottom of the page, however.

    0 讨论(0)
  • 2020-12-24 11:08

    Yep, it's a small mistake.

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

    so not sure if this answers your question but the indexOf the items you are adding keep returning -1. Not to familiar with js but it appears the items do that because they are not in the array yet. I made a jsfiddle of a little modified code for you.

    this.items = [];
    
    add(1);
    add(2);
    add(3);
    
    document.write("added items to array");
    document.write("<br>");
    function  add(item) {
            //document.write(this.items.indexOf(item));
        if(this.items.indexOf(item) <= -1) {
    
          this.items.push(item);
          //document.write("Hello World!");
        }
    }
    
    document.write("array is : " + this.items);
    

    https://jsfiddle.net/jmpalmisano/Lnommkbw/2/

    0 讨论(0)
  • 2020-12-24 11:14

    If you use Lodash, take a look at _.union function:

    let items = [];
    items = _.union([item], items)
    
    0 讨论(0)
提交回复
热议问题