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.
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
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
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
Let's consider we have an array of objects
const users = [{id: 1, name: 'suraj'}, {id: 2, name: 'Mark'}]
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
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 Solutions
How to add an element at the beginning of an array in JavaScript
How to Disable a Button when an Input field is Empty in React
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.