Array.push() and unique items

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

let items = [];
items = _.union([item], items)

Yep, it's a small mistake.

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

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]);
}

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.

Tags:

Javascript