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) {
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);
}
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);
}
}
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);
}
});
I guess ES6 has set data structure, which you can use for unique entries
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);
var helper = {};
for(var i = 0; i < data.length; i++){
helper[data[i]] = 1; // Fill object
}
var result = Object.keys(helper); // Unique items