- How to check if an array contains a value in JavaScript
- You might also like.
- Check if an Item is in an Array in JavaScript – JS Contains with Array.includes()
- How to Check if an Item is in an Array in JavaScript Using Array.includes()
- How to Check if an Item is in an Array in JavaScript Using Array.includes() Starting From a Specified Index
- How to Check if a Substring is in a String in JavaScript Using the includes() Method
- Summary
How to check if an array contains a value in JavaScript
In JavaScript, there are multiple ways to check if an array includes an item. Apart from loops, you can use includes() , indexOf() , find() , etc. to check whether the given value or element exists in an array or not.
The includes method was added in ES6 to determine whether an array contains a specified value. This method returns true if the element exists in the array and false if not. The includes() method is perfect for finding whether the element exists or not as a simple boolean value:
const fruits = ['🍎', '🍋', '🍊', '🍇', '🍍', '🍐'] fruits.includes('🍇') // true fruits.includes('🍉') // false
By default, the includes() method searches the entire array. But you can also pass in a starting index as a second parameter to start the search from a different position:
fruits.includes('🍐', 4) // true fruits.includes('🍊', 4) // false
const symbol = Symbol('🌟') const types = ['Apple', 150, null, undefined, true, 29n, symbol] // strings types.includes('Apple') // true // numbers types.includes(150) // true // null types.includes(null) // true // undefined types.includes(undefined) // true // boolean types.includes(true) // true // BigInt types.includes(29n) // true // Symbol types.includes(symbol // true
const arr = [NaN] // ✅ arr.includes(NaN) // true // ❌ arr.indexOf(NaN) // -1
The simplest and fastest way to check if an item is present in an array is by using the Array.indexOf() method. This method searches the array for the given value and returns its index. If no item is found, it returns -1.
const fruits = ['🍎', '🍋', '🍊', '🍇', '🍍', '🍐'] fruits.indexOf('🍋') // 1 (true) fruits.indexOf('🍍') // 4 (true) fruits.indexOf('🍌') // -1 (false)
By default, the indexOf() method starts searching the given item from the beginning of the array and stops at the end of the array. But you can pass in a position as a second argument to skip the starting elements to be included in the search:
fruits.indexOf('🍋', 1) // 1 (true) fruits.indexOf('🍋', 4) // -1 (false)
Note that if the item is present more than once, the indexOf() method returns the position of the first occurrence. JavaScript provides us an alternate array method called lastIndexOf() . As the name suggests, it returns the position of the last occurrence of the items in an array. The lastIndexOf() starts searching the array from the end and stops at the beginning of the array. You can also specify a second parameter to exclude items at the end.
const fruits = ['🍎', '🍋', '🍊', '🍇', '🍍', '🍐'] fruits.lastIndexOf('🍇') // 3 (true) fruits.lastIndexOf('🍉') // -1 (true) fruits.lastIndexOf('🍋', 4) // 1 (false)
Both indexOf() and lastIndexOf() perform a case-sensitive search and work in all browsers, including IE9 and up.
Unlike includes() , the find() method executes the specified function for each element in the array. It returns the value of the first element in the array that passes the given condition:
const fruits = ['🍎', '🍋', '🍊', '🍇', '🍍', '🍐'] const value = fruits.find(elem => elem === '🍍') console.log(value) // 🍍
Note: In the above example, I have used an ES6 arrow function to loop over elements. Read this article to learn more about arrow functions.
If no element is found where the function returns true , the find() method returns an undefined value:
const value = fruits.find(elem => elem === '🍉') console.log(value) // undefined
You can also get the current element index as the second parameter. This is useful when you want to compare the index too:
fruits.find((elem, idx) => elem === '🍇' && idx > 2) // 🍇 fruits.find((elem, idx) => elem === '🍋' && idx > 2) // undefined
const animals = [ name: '🐱' >, name: '🐒' >, whale: '🐋' >] const found = animals.find(elem => elem.name === '🐒') console.log(found) //
The some() method is similar to the find() except that it returns a boolean value true if the element is found in the array, otherwise false .
const fruits = ['🍎', '🍋', '🍊', '🍇', '🍍', '🍐'] fruits.some(elem => elem === '🍐') // true fruits.some(elem => elem === '🍓') // false
const animals = [ name: '🐱' >, name: '🐒' >, whale: '🐋' >] animals.some(elem => elem.name === '🐒') // true animals.some(elem => elem.name === '🍊') // false
The every() method is like some() except that it makes sure that all elements in the array pass a certain condition:
const numbers = [10, 99, 75, 45, 33] // check if all elements are > 15 const result = numbers.every(num => num > 15) console.log(result) // false
Both indexOf() and includes() methods are case-sensitive. This means that you must specify the same case string to search the array:
const names = ['Ali', 'Atta', 'Alex', 'John'] names.indexOf('atta') // -1 names.includes('atta') // false
For a case-insensitive search, one way is to convert each string in the array to lowercase by using the map() method and then perform the search:
const names = ['Ali', 'Atta', 'Alex', 'John'] names.map(elem => elem.toLowerCase()).indexOf('atta') // 1 names.map(elem => elem.toLowerCase()).includes('atta') // true
Alternatively, you could use the some() method to do both string lowercase and comparison in one step:
names.some(elem => elem.toLowerCase() === 'atta') // true
- Want to know the element position in the array? Use the indexOf() method.
- Want to find the position of the last occurrence of an element? There is a lastIndexOf() method available for this purpose.
- Do you only want to know if the element exists or not? Use the includes() method.
- Do you want to get the matching element too? Use the find() method.
- Working with an array of objects? Use the some() method to check the existence of the matching element.
- Want to perform a case-insensitive search? Use find() or some() method.
- Want to check if all elements in an array satisfy a certain condition? Use the every() method.
- And so on.
To learn more about JavaScript arrays and how to store multiple pieces of information in one single variable, read this article.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
Check if an Item is in an Array in JavaScript – JS Contains with Array.includes()
Ihechikara Vincent Abba
You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string.
It returns true if the item is found in the array/string and false if the item doesn’t exist.
In this article, you’ll see how to use the includes() method in JavaScript to check if an item is in an Array, and if a substring exists within a string.
How to Check if an Item is in an Array in JavaScript Using Array.includes()
Here’s the syntax for using the includes() method to check if an item is in an array:
array.includes(item, fromIndex)
Let’s break down the syntax above:
array denotes the name of the array which will be searched through to check if an item exists.
The includes() method takes in two parameters – item and fromIndex .
- item is the particular item you are searching for.
- fromIndex , which is an optional parameter, specifies the index from which to start the search. If you don’t include this parameter, the default index will be set to 0 (the first index).
Here are some examples to show how to use the includes() method to check if an item exists in an array:
const nums = [ 1, 3, 5, 7]; console.log(nums.includes(3)); // true
In the example above, we created an array called nums with four numbers – 1, 3, 5, 7.
Using dot notation, we attached the includes() method to the nums array.
In the includes() method’s parameter, we passed in 3. This is the item we want to search for.
We got true returned because 3 exists in the nums array.
Let’s try searching for a number that doesn’t exist in the array.
const nums = [ 1, 3, 5, 7]; console.log(nums.includes(8)); // false
As expected, we got false returned in the example above because 8 is not an item in the nums array.
How to Check if an Item is in an Array in JavaScript Using Array.includes() Starting From a Specified Index
In the last section, we saw how to check if an item existed in an array without using the second parameter in the includes() method.
As a reminder, the second parameter is used to specify the index to start from when searching for an item in an array.
The index of an array starts from 0. So the first item is 0, the second item is 1, the third item is 2, and so on.
Here’s an example to show how we can use the includes() method’s second parameter:
const nums = [ 1, 3, 5, 7]; console.log(nums.includes(3,2)); // false
The example above returned false even though we had 3 as an item in the array. Here’s why:
Using the second parameter, we told the includes() method to search for the number 3 but starting from index 2: nums.includes(3,2) .
This is the array: [ 1, 3, 5, 7]
So starting from the second index which is 5, we have only 5 and 7 ([5,7]) to be searched through. This is why searching for 3 from index 2 returned false .
If you change the index to start the search from to 1 then you’d get true returned because 3 can be found within that range. That is:
const nums = [ 1, 3, 5, 7]; console.log(nums.includes(3,1)); // true
How to Check if a Substring is in a String in JavaScript Using the includes() Method
Similar to the previous examples, you have to attach the includes() method to the name of the string to be searched through using dot notation.
Here’s what the syntax looks like:
string.includes(substring, fromIndex)
const bio = "I am a web developer"; console.log(bio.includes("web")); // true
In the example above, the bio variable had a value of «I am a web developer».
Using the includes() method, we searched for the substring «web».
We got true returned because «web» is in the bio string.
You can also use the second parameter to specify where the search will begin, but note that each character in a string represents an index and the spaces between each substring also represents an index.
Here is an example to demonstrate that:
let bio = "I am a web developer"; console.log(bio.includes("web",9)); // false
We are getting false because index 9 is the e in «web».
Starting from index 9, the string would look like this: «eb developer». The substring «web» doesn’t exist in the string so false gets returned.
Summary
In this article, we talked about the includes() method in JavaScript. You use it to check if an item exists in an array. You can also use it to check if a substring can be found within a string.
We saw some examples that explained its use to check for an item in an array starting from the first index, then another example from a specified index.
Lastly, we saw how to use the includes() method to check if a substring exists within a string from the first index and from a specified index.