Explain Codes LogoExplain Codes Logo

How to find if an array contains a specific string in JavaScript/jQuery?

javascript
prompt-engineering
functions
performance
Nikita BarsukovbyNikita Barsukov·Sep 6, 2024
TLDR

The includes method swiftly checks the presence of a string in an array:

const fruits = ['apple', 'banana', 'mango']; const hasBanana = fruits.includes('banana'); // returns true, the minion inside your machine is pretty happy

includes, in its simplicity, acts as a boolean guard saying yes (returns true) or no (returns false) to the existence of the string.

Sure, includes is speedy and efficient, but what about cases demanding more complex evaluations? Well, JavaScript offers a toolbox with indexOf and some.

'indexOf': To use or not to use?

Often indexOf comes as a valuable alternative to includes. It doesn't just verify presence, it also tells you where the string is hiding in the array.

const pets = ['cat', 'dog', 'parrot']; const dogPosition = pets.indexOf('dog'); // dogPosition is now 1, our dog prefers the middle seat

Since -1 indicates the string is playing "hide and seek", indexOf is useful for conditional logic. For legacy browser compatibility, they say "old is gold", hence indexOf is the golden key.

'some': The one-trick pony

some is an array method that validates if atleast one element in the array clears the bar of a test provided by a function - it's a like a strict exam invigilator.

const tools = ['hammer', 'screwdriver', 'wrench']; const hasWrench = tools.some(tool => tool === 'wrench'); // hasWrench is true, Wreck-It-Ralph is ready to roll!

This method transforms into the superhero of your code when the mission involves conditional matching or pattern detection.

The mechanics of case sensitivity and search efficiency

A simple search might quickly turn to "Where's Wally", particularly with case variations or huge datasets. To ensure case variations don't make it "Mission Impossible", normalize all contenders - array items and the search string.

const cities = ['Paris', 'Berlin', 'rome']; const searchCity = 'ROME'; const normalizedSearch = cities.map(city => city.toLowerCase()).includes(searchCity.toLowerCase()); // normalizedSearch is true, Rome wasn't built in a day but it was found in a flash!

When it comes to large arrays, performance is king. indexOf and includes rule with an iron fist, but aliens always have advanced tech, right? And this time, it could be a custom loop in their spaceship.

Manual loop and the magic of polyfills

If you're from the "Do-It-Yourself" club, here's how you can check for string existence with a for loop and a boolean flag:

let books =["Pride and Prejudice", "1984", "The Great Gatsby"]; let specialBook = "1984"; let isFound = false; for(let i = 0; i < books.length; i++) { if(books[i] === specialBook) { isFound = true; break; // Who doesn't love the thrill of an early exit, huh? } } // isFound is true, '1984' reappears from the past!

And, if you're dealing with older browsers, sprinkle some polyfills from MDN to make the old souls understand newer JavaScript methods like includes.

Embracing reusability through function encapsulation

To avoid reinventing the wheel, wrap the check in a function that is reusable and talks your language:

function containsString(array, string) { return array.includes(string); } const vegetables = ['carrot', 'peas', 'lettuce']; const lookingFor = 'peas'; const found = containsString(vegetables, lookingFor); // returns true, an undercover veggie spy has been discovered

By packaging utility functions this way, your code remains DRY (Don’t Repeat Yourself) like Arizona, improving readability and maintainability.

The Coding arena

Migrating from jQuery

While jQuery ruled once, native JavaScript solutions are in the spotlight now. $.inArray, jQuery's version of indexOf, could be replaced with the native method for improved performance and reduced dependency.

String pattern matching

It's not always about strict equality. Sometimes, you need to match strings based on a pattern. That's when filter comes at the rescue, armed with regular expressions:

const wordPattern = /book/i; // The 'i' flag ensures it doesn't judge by case const library = ["Textbook", "Notebook", "Cookbook"]; const filtered = library.filter(item => wordPattern.test(item)); // filtered is ["Textbook", "Notebook", "Cookbook"], speaking of a bookworm's paradise

ES6's got your back

The advent of ES6 brought a revolution making JavaScript coding leaner and meaner. By using methods like includes and some, your code stays ahead of the curve, embracing the future.