Explain Codes LogoExplain Codes Logo

Determine whether an array contains a value

javascript
array-methods
performance-optimization
best-practices
Anton ShumikhinbyAnton Shumikhin·Aug 29, 2024
TLDR

To check if an array contains a value, utilize array.includes(value) for an immediate boolean result or array.indexOf(value) to obtain the position.

// With includes(): const hasValue = [1, 2, 3].includes(2); // true // With indexOf(): const index = [1, 2, 3].indexOf(2); // 1

Test for uncertainty or NaN in arrays with some():

const containsNaN = [1, 2, NaN].some(num => Number.isNaN(num)); // true

For browsers with no native includes(), fall back to indexOf() using a polyfill:

if (!Array.prototype.includes) { Array.prototype.includes = function(searchElement, fromIndex) { 'use strict'; return this.indexOf(searchElement, fromIndex) !== -1; }; }

Dealing with array-like objects

For array-like objects, leverage Array.prototype.includes.call():

function hasElement(element) { // "arguments" is array-like; needs special treatment return Array.prototype.includes.call(arguments, element); } hasElement(1, 2, 3, 4); // true

Writing efficient and maintainable code

  • Avoid over-reliance on third-party libraries. Instead, use JavaScript's native methods.
  • Use right-sized lodash imports if you choose lodash. Import only required functions.
  • Use terse direct application syntax: ["Eat", "Sleep", "Code"].includes("Code") and a friendly alien 👽 will visit you.
  • Validate your code regularly with online tools like CodePen or JSFiddle.

Advanced array checks and modifications

Multiple value checks

// Checking for acceptance letter from multiple universities const myUniversities = ['Harvard', 'MIT', 'Princeton']; const lettersArrived = ['Princeton', 'MIT']; const gotAnOffer = lettersArrived.every(univ => myUniversities.includes(univ)); // returns true

Performance implications

.includes() can be a performance hog on large data sets. Use with caution and always benchmark when in doubt.

Code readability and maintenance

  • Use expressive variable names and detailed code comments.
  • Refer documentation for using techniques and methods aptly, enhancing code quality and readability.

More alternatives in search operations

  • Use Array.prototype.some() if a matching condition is what you are looking for.
  • When you need more control, use Array.prototype.filter() to build your search.

Handling issues with cross-browser support

  • Use polyfills for .includes() from Babel or core-js.
  • MDN provides a includes() polyfill to ensure your code works on older browsers.
  • For wider support, consider using lodash's .includes().