0

I've found lots of questions regarding eliminating duplicates from arrays but I'm trying to identify them. Say I have a multi-dimensional array like

array = [[1,2,3,4],[3,4,5,6],[7,8,3,4]]

I want to return only the values that exist in all the arrays. Thus,

result = [3,4]

I know how to do it with only two arrays

array[0].filter(value => -1 !== array[1].indexOf(value)

However I need to do a similar thing with an n-number of arrays

1
  • You can use flat and then filter: const all_duplicates = array.flat().filter((item, index, arr) => arr.indexOf(item) !== index). Then just use new Set to bring up repeated unique values: const duplicates = [...new Set(all_duplicates)] Commented Dec 16, 2019 at 19:17

2 Answers 2

0

Just take your answer between two arrays and generalize it:

result = array[0];
for (let i = 1; i < array.length; i++) {
  result = getDups(result, array[i]); //getDups is your array[0].filter(value =>
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can iterate over one of the items from the array, (for example the first one) and basically use filter() and every() to get the ones that existing in the rest.

const array = [[1,2,3,4],[3,4,5,6],[7,8,3,4]]

const first = array[0];

const filteredArr = first.filter(item => array.slice(1).every(temp => temp.includes(item)));

console.log(filteredArr);

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.