DEV Community

loading...

How to get the common values of an indefinite number of arrays in Javascript

Marco Pestrin
Building web apllications
Updated on ・1 min read

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"]
]
Enter fullscreen mode Exit fullscreen mode

Desired result:

["ivr", "web", "add"]
Enter fullscreen mode Exit fullscreen mode

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);
})
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (3)

Collapse
kais_blog profile image
Kai • Edited

Here's a much easier way:

const arrays = [
  ["ivr", "web", "wap", "add", "acd"],
  ["web", "add"],
  ["ivr", "wap", "add", "web"],
  ["ivr", "web", "add"],
];

const result = arrays.reduce((carry, array) =>
  carry.filter((element) => array.includes(element))
);

console.log(result); // ["web", "add"]
Enter fullscreen mode Exit fullscreen mode

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:

Collapse
pestrinmarco profile image
Marco Pestrin Author

Amazing! Thank you so much for your tips.. Right, your solution might be better. Now I corrected my code with " for my strings

Collapse
alfredosalzillo profile image
Alfredo Salzillo 🐺
const arrays = [
  ["ivr", "web", "wap", "add", "acd"],
  ["web", "add"],
  ["ivr", "wap", "add", "web"],
  ["ivr", "web", "add"],
];
const commons = [...new Set(arrays.flat())]
  .filter((v) => arrays.filter(v1 => v1 === v).length > 1)
Enter fullscreen mode Exit fullscreen mode