Problem
We are required to write a JavaScript function that takes in two arrays, arr1 and arr2 as first and second arguments respectively.
The function should find the intersection (common elements between both) of the arrays and if there are elements that appear twice in both the arrays, we should include them twice in our result array as well.
For example, if the input to the function is −
const arr1 = [2, 7, 4, 6, 7, 4]; const arr2 = [7, 1, 9, 7, 4, 5];
Then the output should be −
const output= [7, 7, 4];
Example
The code for this will be −
const arr1 = [2, 7, 4, 6, 7, 4]; const arr2 = [7, 1, 9, 7, 4, 5]; const intersect = (arr1 = [], arr2 = []) => { const map = {}; arr1.forEach(a => { map[a] = map[a] ? map[a] + 1 : 1; }) const result = []; for(let key of arr2) { if(key in map && map[key] > 0) { result.push(key); map[key]--; } } return result; }; console.log(intersect(arr1, arr2));
Code Explanation:
The steps we took are −
Loop through the first array(arr1) to find the occurrence of each no. in it.
Loop through the second array(arr12) to find if the element in arr2 exists in mapped arr1.
If it exists, then decrease the value in mapped num1 and push the element in result array.
Output
And the output in the console will be −
[7, 7, 4]