The following function elegantly finds duplicates in 1-dimensional arrays:
const findDuplicates = (dataArray) => {
const duplicates = dataArray.filter((e, index, arr) => arr.indexOf(e) !== index);
return (duplicates);
};
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
[
['123456', 'Smith'],
['787877', 'Jones'],
['763223', 'Waldo'],
['787877', 'Quagmire'],
['854544', 'Miller']
]
returns
[['787877', 'Jones'], ['787877', 'Quagmire']]
(To be clear, I'm only interested in whether the 1st field of each sub-array is a dupe.)
CodePudding user response:
You could take an object and use a boolean values to indicae duplicates. Then filter the array.
const
findDuplicates = data => {
const
keys = data.reduce((r, [v]) => {
r[v] = r[v] !== undefined;
return r;
}, {});
return data.filter(([v]) => keys[v]);
},
data = [['123456', 'Smith'], ['787877', 'Jones'], ['763223', 'Waldo'], ['787877', 'Quagmire'], ['854544', 'Miller']],
result = findDuplicates(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
CodePudding user response:
const findDuplicates = (dataArray) => {
const duplicates = dataArray.filter((e, index, arr) => {
return arr.some((val, i) => (index !== i && val[0] === e[0]))
})
return (duplicates);
};
const result = findDuplicates([
['123456', 'Smith'],
['787877', 'Jones'],
['763223', 'Waldo'],
['787877', 'Quagmire'],
['854544', 'Miller']
])
console.log(result)