published: 26 Jul 2022
2 min read
5 ways to check if an array contains a value in JavaScript
In JavaScript, there are multiple ways to check if an array includes an item. You can always use the for loop or Array.indexOf()
method, but ES6 has added plenty of more useful methods to search through an array and find what you are looking for with ease.
indexOf()
Method
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 item 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 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.
includes()
Method
The includes
method is part of ES6 that can also be used to determine whether an array contains a specified item. 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
Beside strings, the includes()
method also works great with other primitive types:
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
Both includes()
and indexOf()
behave differently with NaN
('Not-a-Number') property:
const arr = [NaN];
// ✅
arr.includes(NaN) // true
// ❌
arr.indexOf(NaN) // -1
The incudes()
method doesn't work in IE and is only available in modern browsers.
find()
Method
Unlike includes()
, the find()
method executes the specified function for each element present in the array. It returns the value of the first element in an array that passes a certain condition:
const fruits = ['🍎', '🍋', '🍊', '🍇', '🍍', '🍐'];
const value = fruits.find(elem => elem === '🍍');
console.log(value); // 🍍
Note: In the above example, I have used an arrow function to loop over elements. Arrow functions are part of ES6 and if you don't know about them, take a look at this article.
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 index of the current element as the second parameter of the function. 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
Another benefit of the find()
method is that it works for other data types like objects as well:
const animals = [{ name: '🐱' }, { name: '🐒' }, { whale: '🐋' }];
const found = animals.find(elem => elem.name === '🐒');
console.log(found); // { name: '🐒' }
The find()
method only works in modern browsers.
some()
Method
The some()
method works quite 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
The some()
method can also be used with an array an objects:
const animals = [{ name: '🐱' }, { name: '🐒' }, { whale: '🐋' }];
animals.some(elem => elem.name === '🐒'); // true
animals.some(elem => elem.name === '🍊'); // false
You can use the some()
method in all modern browsers, and in IE9 and above.
every()
Method
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
Just like some()
, the every()
works in all modern browsers, and IE9 and higher.
Case-Insensitive Search
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
To perform 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
Conclusion
In this article, we looked at 5 different JavaScript Array
's methods to check if an item exists in an array.
A legitimate question you may ask, why do we need all these methods in the first place? Why not have just one method to search through an array?
A simple answer would be that all these methods are intended for different use cases:
- 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()
orsome()
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 use them to store multiple pieces of information in one single variable, take a look at this article.
Are we missing something? Help us improve this article. Reach out to us.
5 ways to check if an array contains a value in JavaScript
In JavaScript, there are multiple ways to check if an array includes an item. You can always use the for loop or Array.indexOf()
method, but ES6 has added plenty of more useful methods to search through an array and find what you are looking for with ease.
indexOf()
Method
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 item 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 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.
includes()
Method
The includes
method is part of ES6 that can also be used to determine whether an array contains a specified item. 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
Beside strings, the includes()
method also works great with other primitive types:
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
Both includes()
and indexOf()
behave differently with NaN
('Not-a-Number') property:
const arr = [NaN];
// ✅
arr.includes(NaN) // true
// ❌
arr.indexOf(NaN) // -1
The incudes()
method doesn't work in IE and is only available in modern browsers.
find()
Method
Unlike includes()
, the find()
method executes the specified function for each element present in the array. It returns the value of the first element in an array that passes a certain condition:
const fruits = ['🍎', '🍋', '🍊', '🍇', '🍍', '🍐'];
const value = fruits.find(elem => elem === '🍍');
console.log(value); // 🍍
Note: In the above example, I have used an arrow function to loop over elements. Arrow functions are part of ES6 and if you don't know about them, take a look at this article.
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 index of the current element as the second parameter of the function. 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
Another benefit of the find()
method is that it works for other data types like objects as well:
const animals = [{ name: '🐱' }, { name: '🐒' }, { whale: '🐋' }];
const found = animals.find(elem => elem.name === '🐒');
console.log(found); // { name: '🐒' }
The find()
method only works in modern browsers.
some()
Method
The some()
method works quite 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
The some()
method can also be used with an array an objects:
const animals = [{ name: '🐱' }, { name: '🐒' }, { whale: '🐋' }];
animals.some(elem => elem.name === '🐒'); // true
animals.some(elem => elem.name === '🍊'); // false
You can use the some()
method in all modern browsers, and in IE9 and above.
every()
Method
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
Just like some()
, the every()
works in all modern browsers, and IE9 and higher.
Case-Insensitive Search
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
To perform 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
Conclusion
In this article, we looked at 5 different JavaScript Array
's methods to check if an item exists in an array.
A legitimate question you may ask, why do we need all these methods in the first place? Why not have just one method to search through an array?
A simple answer would be that all these methods are intended for different use cases:
- 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()
orsome()
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 use them to store multiple pieces of information in one single variable, take a look at this article.
Are you looking for other code tips?
JS Nooby
Javascript connoisseur