Created
August 16, 2020 13:15
-
-
Save lukethacoder/e45199df67514ec0d7576f6fd897a376 to your computer and use it in GitHub Desktop.
Remove duplicate Objects within an array by specific field value
This file contains 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
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