Categories
JavaScript Answers

How to get a list of duplicate objects in an array of objects with JavaScript?

Spread the love

Sometimes, we want to get a list of duplicate objects in an array of objects with JavaScript.

In this article, we’ll look at how to get a list of duplicate objects in an array of objects with JavaScript.

How to get a list of duplicate objects in an array of objects with JavaScript?

To get a list of duplicate objects in an array of objects with JavaScript, we can use the JavaScript array’s reduce method.

For instance, we write:

const values = [{
  id: 10,
  name: 'someName1'
}, {
  id: 10,
  name: 'someName2'
}, {
  id: 11,
  name: 'someName3'
}, {
  id: 12,
  name: 'someName4'
}];

const lookup = values.reduce((a, e) => {
  if (a[e.id]) {
    return {
      ...a,
      [e.id]: a[e.id] + 1
    }
  }
  return {
    ...a,
    [e.id]: 1
  }
}, {});

const dups = values.filter(e => lookup[e.id] > 1)
console.log(dups);

We call values.reduce with a callback that returns an object with the counts of the object give in values given the value of e.id.

If a[e.id] is defined, then we increment it by 1.

Otherwise, we set [e.id] to 1.

Then we get the id‘s of the objects in values with value bigger than 1.

As a result, dups is:

[
  {
    "id": 10,
    "name": "someName1"
  },
  {
    "id": 10,
    "name": "someName2"
  }
]

Conclusion

To get a list of duplicate objects in an array of objects with JavaScript, we can use the JavaScript array’s reduce method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *