How to check if an Array includes a value in JavaScript

#javascript #array

Last updated on Sep 12, 2020 by Suraj Sharma



In this tutorial you will learn 5 ways to check if a JavaScript array includes a value.



1. Array.forEach() method


We can iterate through an array to check if the value is present in the array.

forEach() method takes a callback function, which gets executed once for every element in the array.


const countries = ["India", "England", "USA", "Spain"]

let isFound = false;
countries.forEach((country)=>{
  if (country === 'Spain') {
    isFound = true;
    return;
  }
  isFound = false;
})

console.log(isFound) // true


2. Array.includes() method


includes method returns true if a value is present in an array else it returns false.


const countries = ["India", "England", "USA", "Spain"]

countries.includes("France") 
 // false

countries.includes("England") 
// true


3. Array.indexOf() method


indexOf method returns the first index of the matched element, it returns -1 if the value is not present in the array.

```javascript
const countries = ["India", "England", "USA", "Spain"]

countries.indexOf("France") 
 // -1

countries.indexOf("England") 
// 1


Check for an Object in an Array


Let's consider we have an array of objects


const users = [{id: 1, name: 'suraj'}, {id: 2, name: 'Mark'}]


4. Array.some() method


If you have an array of objects and want to know whether an object is present in the array or not then you can consider using Array.some()

some() method takes a callback function, which gets executed once for every element in the array until it finds an element where the callback returns true.

some() returns true if the object is present in the array else it returns false


const objectToFind = {id:2, name: 'Mark'}

const isObjectFound = users.some((user)=> {
  return user.id === objectToFind.id && user.name === objectToFind.name
})

console.log(isObjectFound) // true


5. Array.find() method


It behaves similar to the some() method but instead of returning a boolean value, it returns the matched value from the array or it returns undefined if the value is not present in the array.


const objectToFind = {id:2, name: 'Mark'}

const foundObject = users.find((user)=> {
  return user.id === objectToFind.id && user.name === objectToFind.name
})

console.log(isObjectFound) // {id:2, name: 'Mark'}

const notfoundObject = users.find((user)=> {
  return user.id === 3 && user.name === 'Nick'
})

console.log(notfoundObject) // undefined


Related Articles



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.