Unique intersection of arrays in JavaScript


We are required to write a JavaScript function that takes in two arrays of numbers, let’s say arr1 and arr2. The function should find the intersection between the elements of the array. i.e., the elements that appear in both the arrays.

The only condition is that if we encountered one element before as intersected, we should not consider it again even if appears again in both the arrays.

For example −

If the input arrays are −

const arr1 = [1, 5, 7, 3, 1];
const arr2 = [1, 7, 3, 1, 6];

Then the output array should be −

const output = [1, 3, 7];

However, the order is not that important, what’s more, important is not to consider repetitive intersection.

Example

Following is the code −

const arr1 = [1, 5, 7, 3, 1];
const arr2 = [1, 7, 3, 1, 6];
const uniqueIntersection = (arr1, arr2) => {
   const map = new Set();
   const res = [];
   arr1.forEach(el => map.add(el));
   arr2.forEach(el => {
      if (map.has(el)) {
         res.push(el);
         map.delete(el);
      };
   });
   return res;
};
console.log(uniqueIntersection(arr1, arr2));

Output

Following is the output on console −

[1, 7, 3]

Updated on: 10-Dec-2020

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements