Skip to content

Instantly share code, notes, and snippets.

@rohitsSpace
Created April 14, 2021 06:13
Show Gist options
  • Save rohitsSpace/240a812983f736507895e8c958a4f665 to your computer and use it in GitHub Desktop.
Save rohitsSpace/240a812983f736507895e8c958a4f665 to your computer and use it in GitHub Desktop.
Get intersection of arrays using recursion
// 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