Some days ago I needed to write an algorithm in javascript to get the common values of an indefinite number of arrays.
Let’s look at the following case:
const listArray = [
["ivr", "web", "wap", "add", "acd"],
["ivr", "wap", "add", "web"],
["ivr", "web", "add"]
]
Desired result:
["ivr", "web", "add"]
In this case the common values are ivr, add and web meanwhile the others were excluded because they were not present in all arrays.
Seen my case, I’m not aware how many element an array can have and also how many arrays can I have. But the once thing that I aware was the possible data within the array.
I fully leaned on this last and only piece of information I had available to avoid too many cycles.
The solution that I used to get this algorithm is:
const listArray = [
["ivr", "web", "wap", "add", "acd"],
["web", "add"],
["ivr", "wap", "add", "web"],
["ivr", "web", "add"]
];
let commonChannels = ["ivr", "wap", "web", "acd", "add"];
listArray.forEach(item => {
commonChannels = commonChannels.filter(ch => item.indexOf(ch) > -1);
})
I have created an array with all possible values (commonChannels).
I started to cycle all arrays then every within item each
Whenever an element was missing it was excluded from the array. To do this I rewrote the base variable (commonChannels)
To exclude the elements I've combined of the Filter and IndexOf methods.
Top comments (3)
Here's a much easier way:
This way, it doesn't matter how many arrays you have and what their possible values are. Also, please note, that your code is partly incorrect. You are missing
"
for your strings.Besides, you can find more tips like this here:
14 Awesome JavaScript Array Tips You Should Know About
Kai ・ Dec 9 ・ 9 min read
Amazing! Thank you so much for your tips.. Right, your solution might be better. Now I corrected my code with " for my strings