The following function elegantly finds duplicates in 1-dimensional arrays:
JavaScript
x
6
1
const findDuplicates = (dataArray) => {
2
const duplicates = dataArray.filter((e, index, arr) => arr.indexOf(e) !== index);
3
return (duplicates);
4
};
5
6
When I send it (for example) this array [‘123456’, ‘787877’, ‘763223’, ‘787877’, ‘854544’] it returns [‘787877’].
What I need is something similar that works for a 2-d array so (for instance) inputting
JavaScript
1
9
1
[
2
['123456', 'Smith'],
3
['787877', 'Jones'],
4
['763223', 'Waldo'],
5
['787877', 'Quagmire'],
6
['854544', 'Miller']
7
]
8
9
returns
[[‘787877’, ‘Jones’], [‘787877’, ‘Quagmire’]]
(To be clear, I’m only interested in whether the 1st field of each sub-array is a dupe.)
Advertisement
Answer
JavaScript
1
16
16
1
const findDuplicates = (dataArray) => {
2
const duplicates = dataArray.filter((e, index, arr) => {
3
return arr.some((val, i) => (index !== i && val[0] === e[0]))
4
})
5
return (duplicates);
6
};
7
8
const result = findDuplicates([
9
['123456', 'Smith'],
10
['787877', 'Jones'],
11
['763223', 'Waldo'],
12
['787877', 'Quagmire'],
13
['854544', 'Miller']
14
])
15
16
console.log(result)