I have an array and I want to check whether a particular item is existing or not.
My array looks,
I want to check "Apple" existing or not... if not exist push it to array.
You can use Array.prototype.some() function. Example:
var arr = [{title: 'Orange'}, {title: 'Apple'}, {title: 'Kiwi'}, {title: 'Banana'}];
function appleExists(){
return arr.some(elem => elem.title == 'Apple');
}
alert(appleExists());
//if (!appleExists()) arr.push({title: 'Apple'});
Just write a basic javascript for-loop:
var found = false;
var toCheck = { parameters: [], title: "Apple" };
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].title === toCheck.title) {
found = true;
break; // no need to search further
}
}
if (!found) {
myArray.push(toCheck);
}
I do this sort of things with underscore
_.contains(fruits, function(f) { return f.title === 'Apple';})
There may be some more concise ways to do this with underscore too.
PS: I looked at the docs docs and I saw the more concise way I had mentioned:
_.findWhere(fruits, {title: 'Apple'});
Try the indexOf method: http://www.w3schools.com/jsref/jsref_indexof_array.asp
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");
angular.foreachto compare object keys.