Skip to content

Instantly share code, notes, and snippets.

@marcelabomfim
Created March 27, 2019 21:51
Show Gist options
  • Save marcelabomfim/395a1790bfd74d192436d15912b178bc to your computer and use it in GitHub Desktop.
Save marcelabomfim/395a1790bfd74d192436d15912b178bc to your computer and use it in GitHub Desktop.
/*
* Remove duplicate object entries from an array
* @param {Object[]} arr - the array of objects
* @param {string} prop - the property used for comparison
*
* @example
* // returns [{ id: 1, name: 'apple', id: 3, name: 'orange'}]
* removeDuplicatesByProp([{ id: 1, name: 'apple' }, { id: 2, name: 'apple' }, { id: 3, name: 'orange' }], 'name');
*
* @returns {Object[]}
*/
const removeDuplicatesByProp = (arr, prop) =>
arr
.map(e => e[prop])
.map((e, i, final) => final.indexOf(e) === i && i)
.filter(e => arr[e])
.map(e => arr[e]);
export default removeDuplicatesByProp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment