Skip to content

Instantly share code, notes, and snippets.

@adamdehaven
Created August 7, 2020 21:31
Show Gist options
  • Save adamdehaven/33af98d21bf18ba2b608ae3948aa279b to your computer and use it in GitHub Desktop.
Save adamdehaven/33af98d21bf18ba2b608ae3948aa279b to your computer and use it in GitHub Desktop.
Remove duplicate objects from JavaScript array
/**
* Returns an array of objects with no duplicates
* @param {Array} arr Array of Objects
* @param {Array} keyProps Array of keys to determine uniqueness
*/
function uniqueArrayofObjects(arr, keyProps) {
return Object.values(arr.reduce((uniqueMap, entry) => {
const key = keyProps.map(k => entry[k]).join('|')
if (!(key in uniqueMap)) uniqueMap[key] = entry
return uniqueMap
}, {}))
}
// Usage Example
const startingArray = [
{ property: 'name', content: 'adam' }, // duplicate
{ itemprop: 'name', content: 'adam' },
{ property: 'twitter', content: '@adamdehaven' },
{ property: 'name', content: 'adam' }, // duplicate
{ property: 'tag', content: 'person' },
{ property: 'tag', content: 'developer' },
{ property: 'name', content: 'adam' }, // duplicate
]
const newArray = uniqueArrayofObjects(startingArray, ['property', 'content', 'itemprop'])
console.log(newArray)
// Output
// (5) [{…}, {…}, {…}, {…}, {…}]
// 0: {property: "name", content: "adam"}
// 1: {itemprop: "name", content: "adam"}
// 2: {property: "twitter", content: "@adamdehaven"}
// 3: {property: "tag", content: "person"}
// 4: {property: "tag", content: "developer"}
// length: 5
// __proto__: Array(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment