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));
1

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.