How to Remove Duplicates from an Array of Objects in TypeScript?

One of my team members struggled to remove duplicates from an array of objects in TypeScript. I suggest a few different methods. In this tutorial, I will explain how to effectively remove duplicates from an array of objects in TypeScript with some examples.

Remove Duplicates from an Array of Objects in TypeScript

When working with arrays of objects, duplicates can arise due to various reasons, such as merging datasets or receiving data from different sources. For instance, consider an array of user objects that might contain multiple entries for the same user.

In those scenarios, we need to remove these duplicates for data integrity and ensure that your application behaves as expected.

Now, let me show you with an example.

Let’s consider an example array of user objects in TypeScript:

const users = [
  { id: 1, name: "John Doe", email: "john.doe@example.com" },
  { id: 2, name: "Jane Smith", email: "jane.smith@example.com" },
  { id: 1, name: "John Doe", email: "john.doe@example.com" },
  { id: 3, name: "Emily Johnson", email: "emily.johnson@example.com" },
  { id: 2, name: "Jane Smith", email: "jane.smith@example.com" }
];

In this array, we have duplicates for “John Doe” and “Jane Smith.” Our goal is to create a new array that contains only unique user objects.

Now, let me show you different methods to remove duplicates from an array of objects in TypeScript.

Method 1: Using filter() and findIndex()

One of the simplest methods to remove duplicates from an array of object in TypeScript is by using the filter() method in conjunction with findIndex(). This approach allows us to iterate through the array and only keep the first occurrence of each object based on a unique identifier.

Implementation

Here’s how you can implement this method:

const uniqueUsers = users.filter((user, index, self) =>
  index === self.findIndex((u) => u.id === user.id)
);

console.log(uniqueUsers);

Explanation

  • The filter() method creates a new array with all elements that pass the test implemented by the provided function.
  • The findIndex() method returns the index of the first element in the array that satisfies the provided testing function.
  • This combination ensures that only the first occurrence of each user, based on their id, is included in the new array.

Output

The output for the above code will be:

[
  { id: 1, name: "John Doe", email: "john.doe@example.com" },
  { id: 2, name: "Jane Smith", email: "jane.smith@example.com" },
  { id: 3, name: "Emily Johnson", email: "emily.johnson@example.com" }
]

Here is the complete code, and you can see the exact output in the screenshot below:

const users = [
    { id: 1, name: "John Doe", email: "john.doe@example.com" },
    { id: 2, name: "Jane Smith", email: "jane.smith@example.com" },
    { id: 1, name: "John Doe", email: "john.doe@example.com" },
    { id: 3, name: "Emily Johnson", email: "emily.johnson@example.com" },
    { id: 2, name: "Jane Smith", email: "jane.smith@example.com" }
  ];

  const uniqueUsers = users.filter((user, index, self) =>
    index === self.findIndex((u) => u.id === user.id)
  );
  
  console.log(uniqueUsers);
Remove Duplicates from an Array of Objects in TypeScript

Check out How to Filter Arrays in TypeScript?

Method 2: Using Set for Unique Values

Another efficient way to remove duplicates from an array of objects is by using a Set in TypeScript. The Set object lets you store unique values of any type, which can be particularly useful for this task.

Implementation

Here’s how you can use a Set to achieve the same result:

const uniqueUserEmails = Array.from(
  new Set(users.map(user => user.email))
).map(email => users.find(user => user.email === email));

console.log(uniqueUserEmails);

Explanation

  • We first create a Set from the array of user emails, ensuring that all emails are unique.
  • We then convert the Set back into an array and map over it to find the corresponding user object for each unique email.

Output

The output will be the same as before:

[
  { id: 1, name: "John Doe", email: "john.doe@example.com" },
  { id: 2, name: "Jane Smith", email: "jane.smith@example.com" },
  { id: 3, name: "Emily Johnson", email: "emily.johnson@example.com" }
]

Read How to Sort Arrays in TypeScript?

Method 3: Using the reduce() Method

The reduce() method can also be used to accumulate values into a single result, making it suitable for removing duplicates.

Implementation

Here’s an example of using reduce():

const users = [
    { id: 1, name: "John Doe", email: "john.doe@example.com" },
    { id: 2, name: "Jane Smith", email: "jane.smith@example.com" },
    { id: 1, name: "John Doe", email: "john.doe@example.com" },
    { id: 3, name: "Emily Johnson", email: "emily.johnson@example.com" },
    { id: 2, name: "Jane Smith", email: "jane.smith@example.com" }
  ];
  
  const uniqueUsersReduce = users.reduce((accumulator, current) => {
    if (!accumulator.ids.has(current.id)) {
      accumulator.ids.add(current.id);
      accumulator.uniqueUsers.push(current);
    }
    return accumulator;
  }, { ids: new Set<number>(), uniqueUsers: [] as typeof users }).uniqueUsers;
  
  console.log(uniqueUsersReduce);

Explanation

  1. We use reduce() to iterate over the users array.
  2. The accumulator object has two properties:
    • ids: a Set to keep track of unique IDs encountered so far.
    • uniqueUsers: an array to store the unique user objects.
  3. For each current user object, we check if its id is already in the ids set:
    • If the id is not in the set, we add it to the set and push the current user object to the uniqueUsers array.
    • If the id is already in the set, we skip that user object.
  4. Finally, we return the uniqueUsers array from the accumulator object.

This approach ensures that only the first occurrence of each unique id is kept in the resulting array, effectively removing any duplicates based on the id property.

Output

The output will be the same as in previous examples:

[
  { id: 1, name: "John Doe", email: "john.doe@example.com" },
  { id: 2, name: "Jane Smith", email: "jane.smith@example.com" },
  { id: 3, name: "Emily Johnson", email: "emily.johnson@example.com" }
]

Here is the exact output in the screenshot below:

How to Remove Duplicates from an Array of Objects in TypeScript

Conclusion

In this tutorial, we explored three effective methods to remove duplicates from an array of objects in TypeScript: using filter() with findIndex(), leveraging Set, and utilizing reduce().

You may also like: