Array.push() if does not exist?
For an array of strings (but not an array of objects), you can check if an item exists by calling .indexOf()
and if it doesn't then just push the item into the array:
var newItem = "NEW_ITEM_TO_ARRAY";
var array = ["OLD_ITEM_1", "OLD_ITEM_2"];
array.indexOf(newItem) === -1 ? array.push(newItem) : console.log("This item already exists");
console.log(array)
It is quite easy to do using the Array.findIndex
function, which takes a function as an argument:
var arrayObj = [{name:"bull", text: "sour"},
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" }
]
var index = arrayObj.findIndex(x => x.name=="bob");
// here you can check specific property for an object whether it exist in your array or not
index === -1 ? arrayObj.push({your_object}) : console.log("object already exists")
You could extend the Array prototype with a custom method:
// check if an element exists in array using a comparer function
// comparer : function(currentElement)
Array.prototype.inArray = function(comparer) {
for(var i=0; i < this.length; i++) {
if(comparer(this[i])) return true;
}
return false;
};
// adds an element to the array if it does not already exist using a comparer
// function
Array.prototype.pushIfNotExist = function(element, comparer) {
if (!this.inArray(comparer)) {
this.push(element);
}
};
var array = [{ name: "tom", text: "tasty" }];
var element = { name: "tom", text: "tasty" };
array.pushIfNotExist(element, function(e) {
return e.name === element.name && e.text === element.text;
});