Best way to find if an item is in a JavaScript array?
Includes()
and indexOf()
are your prime methods in finding an item in a JavaScript array.
For those feeling a bit retro and using older JavaScript versions:
Breaking down the methods
Here's the gist:
includes()
gives us a simple boolean if an item is there.indexOf()
pinpoints the index of an item or returns -1 if the item skipped this array.
What about non-primitive types, like objects? Use some()
:
Support for older browsers
IE6-8 don't know the cool kids yet, you'll need to babysit them:
- A polyfill will make
Array.prototype.includes()
work smoothly. - Wrap
Array.prototype.indexOf()
in a custominclude()
function. - Erik Arvidsson's array extras have your back with robust fallbacks.
Speed check
Performance depends on the type of race your array is in. Long marathon or short sprint? Also, position matters in the game!
- Got a Marathon? Long arrays need more thought for efficiency.
- A sprint? Bingo! Just benchmark your array tasks.
If you're playing the game of exclusion, choose Set
. It's a speedster!
Advanced sleuthing
Your investigation may have complex conditions or items. There's a tool for every job:
find()
more with complex conditions
Here's your chance to dive deeper:
Nested arrays are no hideaway
Nested structures? Fear not, use recursion or lodash to get you through:
Beware of falsely accused negatives
Your magnifying glass sometimes peers too deep. Avoid type coercion by using strict comparison:
Gotchas and Aces
- 911 for
null
orundefined
inputs, they crash parties! - Polyfills should play by the MDN rulebook.
- If you're in the jQuery territory,
$.inArray()
can be your older browser's best friend.
Remember, your function needs constant tests and tireless updates for a rock-solid performance.
Was this article helpful?