#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.
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
<br>
<br>
## Check for an Object in an Array
<br>
Let's consider we have an array of objects
<br>
javascript const users = [{id: 1, name: 'suraj'}, {id: 2, name: 'Mark'}]
<br>
<br>
## 4. Array.some() method
<br>
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`
<br>
javascript const objectToFind = {id:2, name: 'Mark'}
const isObjectFound = users.some((user)=> { return user.id = objectToFind.id && user.name = objectToFind.name })
console.log(isObjectFound) // true
<br>
<br>
## 5. Array.find() method
<br>
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.
<br>
javascript 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
<br>
<br>
**Related Solutions**
- [How to add an element at the beginning of an array in JavaScript](/blog/javascript-array-unshift-method)
- [How to uppercase the First Letter of a String in JavaScript](/blog/uppercase-first-letter-in-javascript)
- [How to get the last element of an Array in JavaScript](/blog/javascript-array-get-last-element)
- [How to convert a Decimal to a Hexadecimal in JavaScript](/blog/decimal-to-hexadecimal-javascript)
<br>
Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.