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

bopritchard
  • 369
  • 3
  • 15
  • 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)]` – Rubens Barbosa Dec 16 '19 at 19:17

2 Answers2

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 =>
}
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
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);
zb22
  • 3,126
  • 3
  • 19
  • 34