Forked from marcelabomfim/removeDuplicatesByProp.js
Last active
November 28, 2019 19:34
-
-
Save VitorLuizC/6ef22217c431101437c1559ee50936ba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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