1

I have a JS array of objects like this:

Ident: "2" Text: "Foo" 

Now I want to check if the object with the Ident equal to 2 is in the array. How can I do this? It's not possible with jQuery.inArray because I don't have the whole object, just the Ident.

3
  • 1
    A regular loop should work fine. If you check the values a lot it makes sense to create a new object (with the data as keys) to cache it (see this jsperf). What have you tried? Commented May 26, 2014 at 14:23
  • 1
    Are you working with an array of objects? Or with an object that serves as associate array? Commented May 26, 2014 at 14:26
  • There's a find function in ES6 and it's supported by some browsers. A polyfill is available. Commented May 26, 2014 at 14:26

3 Answers 3

3

You will indeed have to do the loop the long way here:

function findByIdent(array, ident) { var i; for (i = 0; i < array.length; i++) { if (array[i].Ident === ident) { return i; } } return -1; // not found } 

If it's any consolation, this used to be the way all is-this-element-in-this-array calls were done!

Note that this presumes that you have an array that looks approximately like this:

[{Ident: "2", Text: "foo"}, {Ident: "3", Text: "bar"}] 
Sign up to request clarification or add additional context in comments.

Comments

3

As you had mentioned JQuery, you can use "grep" method:

 if (jQuery.grep(arr, function( n ) { return ( n.Ident == "2" ); }).length) ... 

but it will loop through all elements.

1 Comment

Yes, if you're looking for true/false rather than the index, that's a nice solution.
1
var found = false; for (var i =0;i<somearray.length;i++) { if (somearray[i].Ident === 2) { found = true; break; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.