DEV Community

Cover image for How to remove duplicate objects from a JavaScript array
Adam DeHaven
Adam DeHaven

Posted on • Originally published at adamdehaven.com

How to remove duplicate objects from a JavaScript array

In JavaScript, there seems to be an easy way to pretty much anything (disagree with me in the comments 🤷‍♂️). One of the things that isn't so easy is removing duplicate objects from a JavaScript array of objects. In this quick tip, I'll provide you with a simple function that will return an array of JavaScript objects with duplicates removed.

JavaScript function

First, let's take a look at the function which accepts two arguments:

  • arr - The original array of JavaScript objects (which may contain duplicates)
  • keyProps - An array of object property names that should be checked, in combination, to not allow duplicates.
/**
 * Returns an array of objects with no duplicates
 * @param {Array} arr Array of Objects
 * @param {Array} keyProps Array of keys to determine uniqueness
 */
function getUniqueArray(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
    }, {}))
}
Enter fullscreen mode Exit fullscreen mode

Usage example

In our example below, we have an array of JavaScript objects that we will use in "Project A" to create meta tags for a webpage. We don't want duplicate meta tags on the page, so we will run the original array through our function to remove duplicates.

We only want to remove an object if all properties are the same within the object, so we will pass all available object properties to the function as an array.

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 = getUniqueArray(startingArray, ['property', 'content', 'itemprop'])
Enter fullscreen mode Exit fullscreen mode

Output

When we log the output of the function, we can see that objects with the exact same properties and values have been removed from our array:

console.log(newArray)

// (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)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)