Created
July 26, 2019 08:12
-
-
Save frizar/5898afd22b86953d6badaf383077275e to your computer and use it in GitHub Desktop.
ES6 array of unique objects by prop
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
// https://javascript.info/map-set | |
const uniqueObjectsByProp = (array, prop) => { | |
let map = new Map(array.map(item => [item[prop], item])); | |
return Array.from(map.values()); | |
}; | |
let arr = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }, { id: 1, name: 'Item 1' }]; | |
let uniqueArr = uniqueObjectsByProp(arr, 'id'); | |
console.log(uniqueArr); // [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment