Skip to content

Instantly share code, notes, and snippets.

@frizar
Created July 26, 2019 08:12
Show Gist options
  • Save frizar/5898afd22b86953d6badaf383077275e to your computer and use it in GitHub Desktop.
Save frizar/5898afd22b86953d6badaf383077275e to your computer and use it in GitHub Desktop.
ES6 array of unique objects by prop
// 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