I need to filter an array of form controls to check for duplicate values. I have written the following algorithm to identify and return an array of the controls which have are duplicates. I have not seen this indexOf based approach in any of the sample duplicate checkers one finds in Google. Can anyone here spot a flaw in my code?
// select all keys
const duplicateKeys = values.map((current) => current.name);
// filter duplicate keys
const filteredDuplicateKeys = duplicateKeys.reduce((prev, name, index, names) => {
if (names.indexOf(name) !== names.indexOf(name, index)) {
if (!prev.includes(name)) return prev.concat(name);
}
return prev;
}, []);
// filter original array based on identified duplicate keys
const duplicates = values.reduce((prev, current) => filteredDuplicateKeys.indexOf(current.name) > -1 ? prev.concat(current) : prev, []);