Skip to content

Instantly share code, notes, and snippets.

@marcelabomfim
Created June 15, 2018 16:08
Show Gist options
  • Select an option

  • Save marcelabomfim/4f466f20776121ee4f5004b2d401036b to your computer and use it in GitHub Desktop.

Select an option

Save marcelabomfim/4f466f20776121ee4f5004b2d401036b to your computer and use it in GitHub Desktop.
Javascript | Find common elements in multiple arrays
const findCommonElements = arrays =>
arrays.shift().reduce((res, v) => {
if (res.indexOf(v) === -1 && arrays.every((a) => {
return a.indexOf(v) !== -1
})) res.push(v)
return res
}, []);
// Example
const arrays = [
['apple', 'orange', 'banana', 'pear', 'fish', 'pancake', 'taco', 'pizza'],
['taco', 'fish', 'apple', 'pizza'],
['banana', 'pizza', 'fish', 'apple']
];
console.log(findCommonElements(arrays));
// Will be print: ["apple", "fish", "pizza"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment