- Related Questions & Answers
- Finding intersection of multiple arrays - JavaScript
- Finding intersection of arrays of intervals in JavaScript
- Finding intersection of arrays that contain repetitive entries in JavaScript
- Intersection of two arrays JavaScript
- Unique intersection of arrays in JavaScript
- Intersection of three sorted arrays in JavaScript
- Finding the inclination of arrays in JavaScript
- Finding the continuity of two arrays in JavaScript
- Intersection of two arrays in C#
- Intersection of two arrays in Java
- Intersection of Two Arrays in C++
- Finding gcd of two strings in JavaScript
- Intersection of Two Arrays II in Python
- Intersection of Three Sorted Arrays in C++
- Finding reversed index of elements in arrays - JavaScript

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

We have two arrays of Numbers, and we are required to write a function, let’s say intersection() that computes their intersection and returns an array that contains the intersecting elements in any order. Each element in the result should appear as many times as it shows in both arrays.

For example −

If input is −

arr1 = ['hello', 'world', 'how', 'are', 'you']; arr2 = ['hey', 'world', 'can', 'you', 'rotate'];

Then the output should be −

Output: ['world', 'you'];

Had the arrays been sorted, we could have used the two pointer approach with initially both pointing to 0 the start of the respective array and we could have proceeded with increasing the corresponding pointer and that would have been O(m+n) complex w.r.t. time where m and n are the sizes of array.

But since we have unsorted arrays there is no logic in sorting the arrays and then using this approach, we will check every value of first against the second and construct an intersection array. This would cost us O(n^2) time.

Following is the code −

arr1 = ['hello', 'world', 'how', 'are', 'you']; arr2 = ['hey', 'world', 'can', 'you', 'rotate']; const intersectElements = (arr1, arr2) => { const res = []; const { length: len1 } = arr1; const { length: len2 } = arr2; const smaller = (len1 < len2 ? arr1 : arr2).slice(); const bigger = (len1 >= len2 ? arr1 : arr2).slice(); for(let i = 0; i < smaller.length; i++) { if(bigger.indexOf(smaller[i]) !== -1) { res.push(smaller[i]); bigger.splice(bigger.indexOf(smaller[i]), 1, undefined); } }; return res; }; console.log(intersectElements(arr1, arr2));

This will produce the following output in console −

[ 'world', 'you' ]

Advertisements