Sling Academy
Home/JavaScript/JavaScript: 3 Ways to Find Mutual Elements in 2 Arrays

JavaScript: 3 Ways to Find Mutual Elements in 2 Arrays

Last updated: March 10, 2023

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!

Next Article: JavaScript: Finding the Mean (Average) of an Array

Previous Article: JavaScript: 4 Ways to Compare 2 Arrays

Series: Working with Arrays in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration