0

There is an array containing multiple sub-arrays, each with some elements.

For example:

const myArray = [[1,2,3],[2,3,4,5,6,7],[2,3,4],[2,3,6,11]];

in this case it should return [2,3] as these are the common elements in all sub-arrays.

Is there an efficient way to do that?

I wrote a function that does it for 2 sub-arrays, I don't think it's efficient to call it for every sub-array:

const filteredArray = array1.filter(value => array2.includes(value));
Leo Messi
  • 5,157
  • 14
  • 63
  • 125
  • your case https://stackoverflow.com/questions/11076067/finding-matches-between-multiple-javascript-arrays – Shaybakov May 08 '21 at 19:59

2 Answers2

0

You could do like this:

const myArray = [[1, 2, 3], [2, 3, 4, 5, 6, 7], [2, 3, 4], [2, 3, 6, 11]];

const distinctValues = [...new Set(myArray.flat(1))];

const intersection = distinctValues.filter(x => myArray.every(y => y.includes(x)));

console.log(intersection);
Guerric P
  • 30,447
  • 6
  • 48
  • 86
0

You could reduce the array with filtering the nested arrays with a Set.

const
    data = [[1, 2, 3], [2, 3, 4, 5, 6, 7], [2, 3, 4], [2, 3, 6, 11]],
    common = data.reduce((a, b) => b.filter(Set.prototype.has, new Set(a)));

console.log(common);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392