In this tutorial, let’s look at the different ways to check if an array contains a value in JavaScript. We’ll be looking at several pre-defined methods, and then finish off the tutorial using loops to manually check if an array contains a value.
Let’s get to it then!
The includes() method
The easiest way to check if an array contains a value is by using the ‘includes’ method. This method was created for this purpose.
As the name implies, it checks if the array contains a particular value, and returns true if it does, and false if it does not.
Let’s look at an example.
As you can see below, our array contains the values ‘Grapes’, ‘Mangoes’ and ‘Apples’. When we search for ‘Apples’, we get ‘true’, but for ‘Oranges’ and ‘Apple’, we get ‘false’.
let fruits = ['Grapes','Mangoes','Apples']; console.log(fruits.includes('Apples')); //true console.log(fruits.includes('Oranges')); //false console.log(fruits.includes('Apple')); //false - exact match is expected
Why is that?
Well, ‘Oranges’ is not a part of the array values, so naturally we get back false for that. But we get back false for ‘Apple’ as well when its plural form (‘Apples’) is in fact a part of the array.
Why? Well, your browser doesn’t really know that ‘Apple’ and ‘Apples’ refer to the same object. It just looks at the characters, and makes a match based on that.
So, while looking for a value, make sure you use the exact same spelling used in the array.
Check from a specific position
The beauty of the ‘includes’ method is that you can modify the search to start from a specific position in the string.
As you know, every element of an array has a specific index that starts from 0 and ends at length of the array – 1.
So, the first element has an index of 0, the second has an index of 1, and so on with the last element having an index of length – 1.
So, if you’d like to start the search from the 3rd element, for example, leaving the first two elements out of the search, you can specify the position as 2 (2nd index refers to the 3rd element).
Let’s look at an example:
let fruits = ['Grapes','Mangoes','Apples']; console.log(fruits.includes('Grapes')); //true console.log(fruits.includes('Grapes',1)); //false
As you can see in the example above, the first search yields true because we’re searching the entire array, while the second search yielded a ‘false’ value since we’re searching from the 1st index, leaving out the 0th index (first element, where our value is).
Case insensitive search
Look at the following searches:
console.log(fruits.includes('Grapes')); //true console.log(fruits.includes('grapes')); //false
As you can see ‘Grapes’ gives back ‘true’, while ‘grapes’ gives back ‘false’. Why is that? We’ve discussed this concept earlier in the tutorial as well.
Your browser doesn’t know that ‘Grapes’ and ‘grapes’ are the same. As far as it is concerned ‘G’ has a different character code than ‘g’, so the two strings must be different in value. That’s how computers work because JavaScript at its core is case sensitive.
But there’s a way to make your search insensitive by using regular expressions. Regular expression is a vast topic, and we won’t be able to cover every single aspect of it in this tutorial, so let me just teach you how to make case insensitive searches using it’s the ‘i’ flag, where ‘i’ stands for ‘insensitive’.
console.log(fruits.includes(/Grapes/i)); //true console.log(fruits.includes(/grapes/i)); //false
As you can see, all you had to do was remove the quotes and add front slashes instead and an ‘i’ right after the regular expression, and now your search is case insensitive.
Check using array index
So far, we’ve been looking at using the ‘includes’ method. Though it is indeed one of the best ways to check if an array contains a given value, it does pose some compatibility issues. This method is one of the newer methods and is not compatible with several of the legacy browsers out there.
So instead, you can go for one of the other methods that are just as effective but are better compatible with most browsers.
Let’s look at some of the methods that work with indices now. The premise is that, if the value is present in the array, you’ll get back its index; if not, you’ll get back -1.
The indexOf method
The indexOf method can be used to get the index of an element in an array. How would that help our current problem, you might ask?
Well, if the element is present in the array, this method returns that element’s current index. But, if the element is not present, it’ll return -1. And that’s how we can determine if the array contains our given value or not.
Look at the example below. We’re searching for the index of ‘Grapes’, which is 0 (first element), while ‘Oranges’ has an index of -1, which means that this value is not a part of our array.
fruits.indexOf('Grapes'); // 0 fruits.indexOf('Oranges'); // -1
And in our check, all we’re doing is checking if the result is -1, which means the value is not found in our array. Otherwise, it exists in our array. It’s as simple as that.
if(result === -1) { console.log('Value not found in the array'); } else { console.log('Value found in the array'); }
The findIndex method
Similar to the indexOf method, the findIndex method can also be used to find the index of a value in an array.
The only difference is in the syntax of both the methods. The findIndex method loops through all the elements of the array just like the forEach method, and for every iteration, it stores the current element’s value in a temporary variable (which can be named anything you like).
You can use this temporary variable to do anything you like.
For example, in the following code snippet, for every iteration, we’re storing the current array value in the ‘fruit’ variable, and we’re checking if the current value is equal to ‘Grapes’.
When/If it is equal to ‘Grapes’, the findIndex method will return the corresponding index of the value.
Just like the indexOf method, the forEach method also returns -1 if the value is not present in the array. We can use this condition to check if the value we’re looking for is present in our array or not.
let result = fruits.findIndex(fruit => fruit === 'Grapes'); console.log(result); //0 result = fruits.findIndex(fruit => fruit === 'Oranges'); console.log(result); //-1
More array methods
So far, we’ve been looking at some of the straightforward ways of checking if a value is contained in an array. Why don’t we look at using some non-straightforward methods now?
Using the ‘some’ method
The ‘some’ method, as the name implies, will iterate through the given array, just like findIndex. For every iteration, you can use the temporary variable to perform a condition.
If the condition is true at least once, then the entire search will return ‘true’. Otherwise, you’ll get back ‘false’.
In the below examples, we’re searching for ‘Grapes’ and ‘Oranges’ and we get back true and false respectively. You can further use ‘if else’ statements on these comparisons to print out your desired result.
let result = fruits.some(fruit => fruit === 'Grapes'); console.log(result); //true result = fruits.some(fruit => fruit === 'Oranges'); console.log(result); //false
Using the ‘filter’ method
The ‘filter’ method is used to filter and return a new array based on a given condition. For example, you can just extract the numbers that are less than 10 from a numbers array, and now you’ll have a new array with just one-digit numbers.
We can use this method for our purpose by modifying it a little bit. For every iteration, ask the ‘filter’ method to check if the current element is the same as the value we’re searching for.
If it is, that element will be included in the new array.
Once the ‘filter’ method has filtered the array based on your condition, check if the length of this new array is greater than 0 (not empty). If it is, you can conclude that the value you’re looking for is a part of the array you’re searching in.
let result = fruits.filter(fruit => fruit === 'Grapes'); console.log(result); // ['Grapes'] result = fruits.filter(fruit => fruit === 'Oranges'); console.log(result); // [] if(result.length === 0) { console.log('Value not found in the array'); } else { console.log('Value found in the array'); }
Using the ‘find’ method
You can also use the ‘find’ method. This method also iterates through the given array based on a condition and returns the first occurrence of the element that matches the condition. That’s enough for us.
Unlike the ‘filter’ method though, this method just returns a single value, and not an array. But if there are no elements that match the given condition, it returns ‘undefined’. You can use this condition to check if the value is in the array or not, as shown below:
let result = fruits.find(fruit => fruit === 'Grapes'); console.log(result); // Grapes result = fruits.find(fruit => fruit === 'Oranges'); console.log(result); // undefined if(result === undefined) { console.log('Value not found in the array'); } else { console.log('Value found in the array'); }
Using ‘set’ and ‘has’
In JavaScript, you can convert arrays into sets and use the ‘has’ method to check if the value you’re looking for is a part of the set. The main difference between an array and a set is that an array can have duplicates while a set is a collection of unique values.
Use the ‘new Set’ method to convert your array into a set, and then use the ‘has’ method to check if the value you’re looking for is present. If it is, this method will return ‘true’, and if it isn’t, it will return a ‘false’.
let fruits = ['Grapes','Mangoes','Apples']; fruits = new Set(fruits); console.log(fruits); // Set(3) {'Grapes', 'Mangoes', 'Apples'} console.log(fruits.has('Grapes')); //true console.log(fruits.has(/grapes/i)); //false - regular expressons don't work with the 'has' method console.log(fruits.has('Oranges')); //false
Manually finding the value using loops
Rather than using the pre-defined methods, you can also manually loop through your array and check if the value matches the current element at every iteration.
There are many kinds of loops in JavaScript, but we’ll only be looking at forEach and ‘for’ in this tutorial. The ‘forEach’ loop works better with arrays, though the ‘for’ loop is the original, and the most popular way of traversing through an array.
Using the ‘forEach’ loop
Use the ‘forEach’ loop to traverse through the array. For every iteration, the ‘forEach’ loop stores the current element in a temporary variable and this variable can be used to perform any calculations you want.
In our case, we’ll be checking if the current element is the same as the value we’re looking for.
If it is, we’ll store ‘Value is present in the array’ in the ‘result’ variable. If the match was never found, the ‘result’ variable will continue to have the default ‘Value is not present in the array’ that we created at the start of the function.
Finally, return ‘result’ and print it from your calling function, as shown below:
let fruits = ['Grapes','Mangoes','Apples']; function isValueInArray(arr,value) { let result= 'Value is not present in the array'; arr.forEach(a => { if(a === value) { result = 'Value is present in the array.'; } }); return result; } console.log(isValueInArray(fruits,'Grapes')); console.log(isValueInArray(fruits,'Oranges'));
Using the ‘for’ loop
The ‘for’ loop works similar to the ‘forEach’ loop. Let’s iterate through the length of the array and check if arr[i] matches the given value at every iteration, as shown below:
function isValueInArray(arr,value) { for(let i = 0; i < arr.length; i++) { if(arr[i] === value) { return 'Value is present in the array'; } } return 'Value is not present in the array'; }
That’s it! We’ve looked at the different ways of checking if an array contains a given value in JavaScript. We looked at a few direct and non-direct pre-defined methods and finally, we learned how to manually check for the value by using loops.