0

I have an array and I want to check whether a particular item is existing or not.

My array looks,

enter image description here

I want to check "Apple" existing or not... if not exist push it to array.

1
  • You can use angular.foreach to compare object keys. Commented May 12, 2016 at 7:03

4 Answers 4

2

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'});

https://jsfiddle.net/4qz5v7w0/1/

Sign up to request clarification or add additional context in comments.

Comments

1

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);
}

JSFIDDLE

1 Comment

any idea without for loop ?
1

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'});

Comments

-1

Try the indexOf method: http://www.w3schools.com/jsref/jsref_indexof_array.asp

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");

1 Comment

This won't work, because he has an array of objects, not just plain strings

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.