

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding array intersection and including repeating elements in JavaScript
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]
- Related Questions & Answers
- Commons including duplicates in array elements in JavaScript
- Finding first non-repeating character JavaScript
- Finding intersection of multiple arrays - JavaScript
- Finding the largest non-repeating number in an array in JavaScript
- Finding upper elements in array in JavaScript
- Finding intersection of arrays of intervals in JavaScript
- Finding length of repeating decimal part in JavaScript
- Sorting array of exactly three unique repeating elements in JavaScript
- Finding elements whose successors and predecessors are in array in JavaScript
- Sorting an array including the elements present in the subarrays in JavaScript
- Finding the intersection of arrays of strings - JavaScript
- JavaScript construct an array with elements repeating from a string
- Sum of all the non-repeating elements of an array JavaScript
- Finding intersection of arrays that contain repetitive entries in JavaScript
- Finding desired sum of elements in an array in JavaScript