JavaScript: 3 Ways to Find Mutual Elements in 2 Arrays

Updated: March 10, 2023 By: Khue Post a comment

This concise, code-centric article will provide a couple of different ways to find mutual elements (the intersection) in 2 arrays in JavaScript.

Using the filter() method

In the example below, we will apply the filter() method to the first array and pass a callback function to it that checks if each value in the first array is included in the second array. The filter() method will return a new array with only the elements that pass the test, which will be the common elements in both arrays.

The code:

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [4, 5, 6, 7, 8, 9, 1];

const intersection = arr1.filter((value) => arr2.includes(value));

console.log(intersection); 

Output:

[ 1, 4, 5 ]

Using a for…of loop

In the following example, we will create an empty array that is used to hold the mutual elements of 2 given arrays. Next, we will iterate over the first array using a for…of loop and check if each element is included in the second array.

Example:

const arr1 = ['s', 'l', 'i', 'n', 'g', 'a', 'c', 'a', 'd', 'm', 'y'];
const arr2 = ['h', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'];

const commonItems = [];

for (const value of arr1) {
  if (arr2.includes(value)) {
    commonItems.push(value);
  }
}

console.log(commonItems);

Output:

[ 'l', 'd' ]

Note that we only get the unique common elements (a value won’t appear twice).

Using the Set data structure

Another solution to find mutual elements in 2 arrays in JavaScript is to use a set data structure that stores only unique values. You can create a set from one array and then use the has method to check if an element of another array is present in the set. You can also use the spread operator (…) to convert the set back to an array.

Example:

// function to find common items from two arrays
const findCommonItems = (arr1, arr2) => {
  let set1 = new Set(arr1);
  let commonItems = arr2.filter((item) => set1.has(item));
  return [...commonItems];
};

// example arrays
let array1 = [1, 2, 3, 4, 5, 9, 0];
let array2 = [3, 4, 5, 6, 7, 8, 7, 2];

// call the function and print the result
console.log(findCommonItems(array1, array2));

Output:

[ 3, 4, 5, 2 ]

Afterword

We’ve seen some approaches to getting mutual elements in 2 given arrays. The first approach is quick and concise (it’s a kind of single-line solution), and you may prefer it rather than other ones (I’m just guessing).

If you find errors or anachronisms in the code examples, please let me know by leaving comments. I will review and update them as soon as possible. Happy coding & have a nice day!