Removing Duplicate Objects From An Array By Property Name In Javascript

If you have an array of objects and you want to filter the array to remove duplicate objects but do so based on a provided key/property, this might prove to be a problem you would expect Javascript to address natively. If you are using Lodash then you have many methods at your disposal that can help.

Fortunately, if you are working with ES6 and up, writing some basic Javascript using the filter and map functions makes this possible.

function removeDuplicates(myArr, prop) {
    return myArr.filter((obj, pos, arr) => {
        return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos;
    });
}

The code does a basic filter which is akin to a for..loop where you return true or false to remove or keep the item. We can use the map method to create a temporary array, then we use the indexOf method to see if we can find the same object inside of our map. If we do, then we know it is a duplicate.

Nothing overly fancy or complicated here, but undoubtedly useful.