Created
April 14, 2021 06:13
-
-
Save rohitsSpace/240a812983f736507895e8c958a4f665 to your computer and use it in GitHub Desktop.
Get intersection of arrays using recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example Arrays | |
const arr1 = [1,2,3] | |
const arr2 = [10,1,2] | |
const arr3 = [1, 12,13, 2] | |
const getIntersection = (arr1, arr2, ...rest) => { | |
const interSection = arr1.filter(x => arr2.includes(x)) | |
// if we got more than two arrays then we will check rest length | |
// it its more than 0 then we will call that function again. | |
if (rest.length === 0) { return interSection; } | |
return getIntersection(interSection, ...rest); | |
}; | |
// Calling the function and print on the console | |
console.log(getIntersection(arr1, arr2, arr3)); // [1,2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment