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) {
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]
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.
Yep, it's a small mistake.
if(this.items.indexOf(item) === -1) {
this.items.push(item);
console.log(this.items);
}
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/
If you use Lodash, take a look at _.union function:
let items = [];
items = _.union([item], items)