DEV Community

John Au-Yeung
John Au-Yeung

Posted on • Originally published at thewebdev.info

How to Check if an Array Includes a Value in JavaScript?

Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62

Subscribe to my email list now at http://jauyeung.net/subscribe/

Checking if an array includes a value is something that we’ve to do often in a JavaScript app.

In this article, we’ll look at how to check if an array includes a given value in JavaScript.

Array.prototype.includes

The includes method is a method that’s included with the array instance.

It takes a value and compares it with === to check if an element is included.

For instance, we can write:

console.log(['apple', 'orange', 'grape'].includes('orange'));
Enter fullscreen mode Exit fullscreen mode

If it’s included, then it returns true .

Otherwise, it returns false .

Array.prototype.indexOf

We can also use the indexOf method of an array instance to check if it includes a given element.

It also uses === for comparison.

And it returns the index of the first instance of an item if it exists.

Otherwise, it returns -1.

To use it, we write:

console.log(['apple', 'orange', 'grape'].indexOf('orange') >= 0);
Enter fullscreen mode Exit fullscreen mode

Write Our Own

We can write our own function to search for a value.

For instance, we can write:

function contains(a, obj) {
  let i = a.length;
  while (i--) {
    if (a[i] === obj) {
      return true;
    }
  }
  return false;
}

console.log(contains(['apple', 'orange', 'grape'] , 'orange'));
Enter fullscreen mode Exit fullscreen mode

We create the contains function that uses a while loop to search for an item.

If a[i] has the same value as obj then we return true .

If we loop through the whole a array and didn’t find anything that matches, then we return false .

Array.prototype.some

The some method is another array instance method that comes with JavaScript arrays.

It lets us pass in a callback to check if any items match the given condition.

For instance, we can write:

const items = [{
  a: '1'
}, {
  a: '2'
}, {
  a: '3'
}]

console.log(items.some(item => item.a === '3'))
Enter fullscreen mode Exit fullscreen mode

We have an items array that has a bunch of objects.

And we call items.some with a callback to check if any items entry with a property equal to 3 exists.

some returns true if an item that matches the given condition exists and false otherwise.

Conclusion

There’re many ways to find if an array item exists in JavaScript.

Top comments (0)