http://stackoverflow.com/questions/143847/best-way-to-find-if-an-item-is-in-a-javascript-array
Best way to find if an item is in a JavaScript array? [duplicate]
up vote589down votefavorite 153 |
This question already has an answer here: What is the best way to find if an object is in an array? This is the best way I know:
|
||||||||||||||||
marked as duplicate by Gothdojavascript Jan 6 at 21:04This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question. |
|||||||||||||||||
|
8 Answers
up vote565down voteaccepted |
EDIT: This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it‘s not present:
|
||||||||||||||||
|
up vote188down vote |
If you are using jQuery:
For more information: http://api.jquery.com/jQuery.inArray/
|
||||
|
up vote31down vote |
First, implement
It‘s changed to store the length so that it doesn‘t need to look it up every iteration. But the difference isn‘t huge. A less general purpose function might be faster:
I prefer using the standard function and leaving this sort of micro-optimization for when it‘s really needed. But if you‘re keen on micro-optimization I adapted the benchmarks that roosterononacid linked to in the comments, to benchmark searching in arrays. They‘re pretty crude though, a full investigation would test arrays with different types, different lengths and finding objects that occur in different places.
|
||||||||||||||||
|
up vote9down vote |
If the array is unsorted, there isn‘t really a better way (aside from using the above-mentioned indexOf, which I think amounts to the same thing). If the array is sorted, you can do a binary search, which works like this:
Binary search runs in time proportional to the logarithm of the length of the array, so it can be much faster than looking at each individual element.
|
||||||||||||||||
|
up vote9down vote |
assuming .indexOf() is implemented
!!! do not make
the use of 2nd arg (flag) forces comparation by value instead of reference
|
|||
add a comment |
up vote3down vote |
It depends on your purpose. If you program for the Web, avoid
|
||||||||||||
|
up vote3down vote |
A robust way to check if an object is an array in javascript is detailed here: Here are two functions from the xa.js framework which I attach to a
If you then want to check if an object is in an array, I would also include this code:
And finally this in_array function:
|
||||||||||||
|
up vote3down vote |
Here‘s some meta-knowledge for you - if you want to know what you can do with an Array, check the documentation - here‘s the Array page for Mozilla https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array There you‘ll see reference to indexOf, added in Javascript 1.6
|
||||||||||||
|