Problem
How can I add to an array if no values are present? Here’s my collection:
[
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" }
]
I don’t want anything to happen if I try to push into the array again with either the name “tom” or the text “tasty”… but if none of those are present, I want it to. push()
I’m not sure how I’m going to accomplish it.
Asked by tarnfeld
Solution #1
You can check if an item exists in an array of strings (but not in an array of objects) by using. If indexOf() does not return true, simply insert the item into the array:
Answered by Jiří Zahálka
Solution #2
Using the Array, this is pretty simple. The function findIndex accepts 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")
Answered by Ashish Yadav
Solution #3
You may add a custom method to the Array prototype:
// 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;
});
Answered by Darin Dimitrov
Solution #4
http://api.jquery.com/jQuery.unique/
var cleanArray = $.unique(clutteredArray);
makeArray could be of interest to you as well.
Check if it exists before pushing, as shown in the preceding example. In retrospect, I see it also says you may declare it as part of the prototype (I guess that’s termed Class Extension), so there’s no significant improvement below.
However, I’m not sure if indexOf is a faster option than inArray. probably.
Array.prototype.pushUnique = function (item){
if(this.indexOf(item) == -1) {
//if(jQuery.inArray(item, this) == -1) {
this.push(item);
return true;
}
return false;
}
Answered by MistereeDevlord
Solution #5
Like this?
var item = "Hello World";
var array = [];
if (array.indexOf(item) === -1) array.push(item);
With object
var item = {name: "tom", text: "tasty"}
var array = [{}]
if (!array.find(o => o.name === 'tom' && o.text === 'tasty'))
array.push(item)
Answered by Ronnie Royston
Post is based on https://stackoverflow.com/questions/1988349/array-push-if-does-not-exist