Skip to content

Instantly share code, notes, and snippets.

@VitorLuizC
Forked from marcelabomfim/removeDuplicatesByProp.js
Last active November 28, 2019 19:34
Show Gist options
  • Save VitorLuizC/6ef22217c431101437c1559ee50936ba to your computer and use it in GitHub Desktop.
Save VitorLuizC/6ef22217c431101437c1559ee50936ba to your computer and use it in GitHub Desktop.
/*
* Returns a new array without items whose property received is duplicated.
*
* @example
* removeDuplicatesByProp([
* {id: 1, name: 'apple'},
* {id: 2, name: 'apple'},
* {id: 3, name: 'orange'}
* ], 'name');
* //=> [{id: 1, name: 'apple'}, {id: 3, name: 'orange'}]
*
* @param {T[]} objects - An array of objects.
* @param {keyof T} prop - A property used for comparison.
* @returns {T[]}
* @template T
*/
const removeDuplicatesByProp = (objects, property) => {
const values = new Set();
return objects.filter(object => {
const value = object[property];
if (values.has(value))
return false;
values.add(value);
return true;
});
};
export default removeDuplicatesByProp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment