Finding intersection of arrays that contain repetitive entries in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in two arrays of numbers, lets call them arr1 and arr2.

The function should build a third array based on the two input arrays that contains all the elements that are common to both arr1 and arr2.

Note that if there are more than one same element that are present in both the arrays then we have to consider all such instances of that element.

For example −

If the input arrays are −

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

Then the output array should be −

const output = [2, 2, 4, 4];

Example

Following is the code −

const arr1 = [1, 2, 2, 4, 4, 5, 6];
const arr2 = [3, 2, 4, 2, 4, 9];
const findIntersection = (arr1 = [], arr2 = []) => {
   const map = new Map();
   for (const el of arr2) {
      const count = map.get(el) || 0;
      map.set(el, count + 1);
   };
   return arr1.filter(el => {
      let count = map.get(el);
      if (count) {
         map.set(el, --count);
         return true;
      }
      return false;
   });
};
console.log(findIntersection(arr1, arr2));

Output

Following is the console output −

[2, 2, 4, 4]
raja
Published on 18-Jan-2021 05:05:37
Advertisements