How to get the common values from two arrays in JavaScript?

December 3, 2020 - 2 min read

To get the common values from 2 arrays in JavaScript, we can use the filter() method on any one of the array and then check to see if the current value is included in the second array using the includes() method on that array.

Consider these 2 arrays with some elements repeated on both of the arrays,

// arrays
const arr1 = [1, 2, 3, 4];
const arr2 = [2, 3, 4, 5];

Now let's get the common elements from both arrays.

We can acheive this by using the filter() method on any one of the array. Let's take arr1 and use the filter() method on that like this,

// arrays
const arr1 = [1, 2, 3, 4];
const arr2 = [2, 3, 4, 5];

// use filter() method
// on arr1
const commonElements = arr1.filter((element) => {
  // some code here!
});

Now inside this filter() method all we have to do is to check whether the element is present in the arr2.

We can check that using the includes() method in the arr2 and returning the boolean value returned from the includes() method.

It can be done like this,

// arrays
const arr1 = [1, 2, 3, 4];
const arr2 = [2, 3, 4, 5];

// use filter() method
// on arr1
const commonElements = arr1.filter((element) => {
  // check if the element
  // is present in arr2
  // and return the boolean value
  return arr2.includes(element);
});

console.log(commonElements); // [2,3,4]

Great! 🔥 We got the common elements from both the arrays.

See this example live in JSBin.

Feel free to share if you found this useful 😃.