Explain Codes LogoExplain Codes Logo

Best way to find if an item is in a JavaScript array?

javascript
array-methods
performance
polyfills
Alex KataevbyAlex Kataev·Aug 8, 2024
TLDR

Includes() and indexOf() are your prime methods in finding an item in a JavaScript array.

const numArray = [1, 2, 3]; const doesExist = numArray.includes(2); // true, 2 seems to have taken a tour of our numArray.

For those feeling a bit retro and using older JavaScript versions:

const doesExistOld = numArray.indexOf(2) > -1; // true, 2 made its mark in the days of IE8 and prior.

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():

// We've got VIP guests, they come as objects. const guests = [{ name: 'John', diet: 'vegan' }, { name: 'Emma', glutenFree: true }]; // Let's check if Emma made it. const isEmmaHere = guests.some(guest => guest.name === 'Emma'); // true, Emma is having a ball!

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 custom include() 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!

// Here comes our all-star player, Set! const superSet = new Set([1, '2', 3, { name: 'Emma' }]); // Set, is Emma with you? const isEmmaInSet = superSet.has({ name: 'Emma' }); // No, Set doesn't accept VIP guests without strict authentication.

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:

// We're after Emma, but does she avoid gluten? const found = guests.find(guest => guest.name === 'Emma' && guest.glutenFree); // Found Emma, and she's gluten-free!

Nested arrays are no hideaway

Nested structures? Fear not, use recursion or lodash to get you through:

// Let's spend a day at the circus! const circus = [[1, 2], [3, 4], [5, 6]]; const foundFour = circus.some(tent => tent.includes(4)); // true, number 4 is having a fan moment in the circus!

Beware of falsely accused negatives

Your magnifying glass sometimes peers too deep. Avoid type coercion by using strict comparison:

const mixedArray = [1, '2', 3]; const isItHere = mixedArray.includes('2'); // true, String '2' is here with its single quotes. const isItReallyHere = mixedArray.includes(2); // false, Number 2 didn't make it to the party.

Gotchas and Aces

  • 911 for null or undefined 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.