Skip to content

Instantly share code, notes, and snippets.

@lukethacoder
Created August 16, 2020 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukethacoder/e45199df67514ec0d7576f6fd897a376 to your computer and use it in GitHub Desktop.
Save lukethacoder/e45199df67514ec0d7576f6fd897a376 to your computer and use it in GitHub Desktop.
Remove duplicate Objects within an array by specific field value
function removeDuplicateObjectsByKey(array, fieldToDuplicateCheck) {
const newArray = []
const arrayKeys = []
array.forEach((item) => {
// check if we don't already have the value within the arrayKeys array
if (!arrayKeys.includes(item[fieldToDuplicateCheck])) {
// push this value to the arrayKeys array
arrayKeys.push(item[fieldToDuplicateCheck])
// push this object to the newArray array
newArray.push(item)
}
})
// return the newArray with the filtered out duplicate objects
return newArray
}
// A test array of objects. In a real world situation you would have more than just the 'name' key on the objects
const initialArrayOfObjects = [
{
name: 'πŸ‘',
},
{
name: 'πŸ‘',
},
{
name: '🐫',
},
{
name: 'πŸ¦•',
},
{
name: 'πŸ¦•',
},
]
// will filter out the duplicates by the 'name' field
let removeDuplicateObjects = removeDuplicateObjectsByKey(initialArrayOfObjects, 'name')
// [ { name: 'πŸ‘' }, { name: '🐫' }, { name: 'πŸ¦•' } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment