Created
June 15, 2018 16:08
-
-
Save marcelabomfim/4f466f20776121ee4f5004b2d401036b to your computer and use it in GitHub Desktop.
Javascript | Find common elements in multiple arrays
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
| 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