Languages
[Edit]
EN

JavaScript - check if array contains value

3 points
Created by:
mkrieger1
726

In this article, we would like to show you how to check if array contains value using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const array = ['a', 'b', 'c'];

console.log(array.indexOf('b') !== -1);  // true

Hint: this solution works even in older web browsers and Node.js.

or:

// ONLINE-RUNNER:browser;

const array = ['a', 'b', 'c'];

console.log(array.includes('b'));  // true

Warning: Array includes() was introduced in ES6 (around 2016).

 

Practical examples

1. Array indexOf() method

In this example, we use includes() method to check if letters array contains specific characters.

// ONLINE-RUNNER:browser;

const letters = ['a', 'b', 'c'];

console.log(letters.indexOf('b') !== -1);  // true
console.log(letters.indexOf('x') !== -1);  // false

with numbers:

// ONLINE-RUNNER:browser;

const numbers = [1, 2, 3];

console.log(numbers.indexOf(1) !== -1);  // true
console.log(numbers.indexOf(4) !== -1);  // false

2. Array includes() method

In this example, we use includes() method to check if letters array contains specific characters.

// ONLINE-RUNNER:browser;

const letters = ['a', 'b', 'c'];

console.log(letters.includes('b'));  // true
console.log(letters.includes('x'));  // false

with numbers:

// ONLINE-RUNNER:browser;

const numbers = [1, 2, 3];

console.log(numbers.includes(1));  // true
console.log(numbers.includes(4));  // false

 

Reusable function

In this section, you can find a function that works in older and modern web browsers or Node.js.

// ONLINE-RUNNER:browser;

const containsItem = (array, item) => array.indexOf(item) !== -1;


// Usage example:

const letters = ['a', 'b', 'c'];

console.log(containsItem(letters, 'b'));  // true
console.log(containsItem(letters, 'x'));  // false

 

References

  1. Array.prototype.includes() - JavaScript | MDN

Alternative titles

  1. JavaScript - check if array includes value
  2. JavaScript - check if element is present in array
  3. JavaScript - check if item is in array
  4. JavaScript - check if value exists in array
  5. JavaScript - check if element exists in array
  6. JavaScript - check if item exists in array
  7. JavaScript - check array for value
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join