Skip to content

Instantly share code, notes, and snippets.

@d4lek
Last active December 2, 2020 14:25
Show Gist options
  • Select an option

  • Save d4lek/eefcc0fc785271d094ec0080dcdc8b05 to your computer and use it in GitHub Desktop.

Select an option

Save d4lek/eefcc0fc785271d094ec0080dcdc8b05 to your computer and use it in GitHub Desktop.
findDuplicates in an array of objects
const defaultOptions = {
addError: <T extends { [key: string]: unknown }>(
item: T,
fieldName: string
) => ({
id: item.id,
value: item[fieldName],
}),
};
/**
*
* @param items - array of objects to be looked at
* @param fieldNames - array of string key names from the objects from the array above to check for duplicates
* ```
* const duplicates = findDuplicates(items, ['name', 'email'])
*
* if (duplicates) {
* // do something
* }
* ```
*/
export default function findDuplicates<T extends { [key: string]: unknown }>(
items: T[] = [],
fieldNames: string[] = [],
{ addError } = defaultOptions
): undefined | Map<string, { id: number; value: unknown }> {
const errors = new Map();
fieldNames.forEach((fieldName) => {
const seen = new Set();
// eslint-disable-next-line array-callback-return
items.some((item) => {
/** if the value doesn't exist, skip it */
if (!item[fieldName]) return;
/** otherwise check if size differs after insertion and add an error if it doesn't */
if (seen.size === seen.add(item[fieldName]).size) {
errors.set(fieldName, addError(item, fieldName));
}
});
});
return errors.size > 0 ? errors : undefined;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment