- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]
- Related Articles
- Intersection of two arrays JavaScript
- Intersection of three sorted arrays in JavaScript
- Finding intersection of multiple arrays - JavaScript
- Finding intersection of arrays of intervals in JavaScript
- Finding the intersection of arrays of strings - JavaScript
- Finding intersection of arrays that contain repetitive entries in JavaScript
- Intersection of two arrays in C#
- Intersection of two arrays in Java
- Intersection of Two Arrays in C++
- Intersection of Three Sorted Arrays in C++
- Intersection of Two Arrays II in Python
- Merging two arrays in a unique way in JavaScript
- Combine unique items of an array of arrays while summing values - JavaScript
- How to find the intersection of two arrays in java?
- How to get the intersection of two arrays in MongoDB?

Advertisements