Javascript: Check an array value is included in another array
Chris Dixon
Posted on May 18, 2020
A common situation is when we have 2 arrays, and want to know if the value of one is included in the other:
const array1= ["cheese", "dough", "sauce", "pepperoni"]
const array2= ["mozzarella", "peppers", "chicken", "cheese"]
Here we see that "cheese" is in both arrays, but how we use Javascript to check?
First of all, we need to decide what we want to be returned:
- Do we want a boolean, if there is a match return true, if not return false
- Or, do we want the matching values returned i.e "cheese"
For option 1, we can use the some array method to get a boolean value. This is simple enough for checking one array, but we want to compare 2. So, we can also combine with the includes array method:
const isIncluded = array1.some(value => array2.includes(value))
// true
This will get each "value" from array1, then check this value is included in array2.
The true or false value is then stored in the isIncluded constant.
Next we can also store these matching values too. We can do this with the filter array method, this will create a new array with the matching values:
const values = array1.filter(value => array2.includes(value))
// "cheese"
The code above is the same as the first example, but using filter in place of some. Again checking each value in array1 is included in array2, then storing in the values constant.
You can also find a working Codepen demo here too: https://codepen.io/chrisdixon161/pen/OJyPJdB
Posted on May 18, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.