I’m searching for a way for extracting common values in at least two arrays in the list of arrays in JS.
e.g. [["google", "amazon", "reddit"], ["telegram", "reddit", "discord"], ["firefox", "telegram", "chrome"]]
to ["reddit", "telegram]
The point is 1. the arrays can be any length 2. common at least two (or any specified number) of arrays but not all of the arrays.
I looked a countless numbers of SO posts and also looked the lodash functions, they are all talking either "of two arrays" or "of all arrays from multiple arrays", none of them were takling "of two/arbitrary arrays from multiple arrays". So I’m here to ask.
Thanks.
2
Answers
You can create a function by passing the array and the occurrences. You can maintain an occurrences object to store the item occurrences in the arrays. Then iterates over each array, incrementing the occurrence count in the occurrences object.
If occurrences match then store the item in the result array.
Finally, return the result.
Demo:
If you don’t need flexibility with the amount of arrays that have a common value, you can do this:
Demo: