How to Remove Duplicates from an Array of Objects using TypeScript ?
Last Updated :
03 May, 2024
We are given an array of objects and we have to check if there are duplicate objects present in the array and remove the duplicate occurrences from it. Otherwise, return the array as it is.
Examples of Removing Duplicates from an Array of Objects using TypeScript
1.Using filter() and findIndex() methods
This approach involves using the filter() function along with the findIndex() method to create a new array containing only the unique objects.
Syntax:
const uniqueArray = originalArray.
filter((obj, index, self) =>index ===
self.findIndex((o) => o.propertyToCheck === obj.propertyToCheck)
);
Example: The below code uses filter() and the findIndex() method to remove duplicate objects from an array.
JavaScript
interface Person {
id: number;
name: string;
}
const persons: Person[] = [
{ id: 1, name: 'Ram' },
{ id: 2, name: 'Shyam' },
{ id: 1, name: 'Ram' },
{ id: 3, name: 'Sita' },
];
const uniquePersons = persons.
filter((person, index, self) => index ===
self.findIndex((p) => p.id === person.id)
);
console.log(uniquePersons);
Output:
[
{ "id": 1, "name": "Ram" },
{ "id": 2, "name": "Shyam" },
{ "id": 3, "name": "Sita" }
]
2.Using Set and Array.from() method
This approach utilizes a Set to keep track of unique values based on the selected property. The Array.from() method is used to convert the created Set into a array.
Syntax:
const uniqueArray = Array.from(new Set
(originalArray.map((obj) => obj.propertyToCheck)));
Example: The below code explains the use of the Set and the Array.from() method to remove duplicate objects.
JavaScript
interface Person {
id: number;
name: string;
}
const persons: Person[] = [
{ id: 1, name: 'Ram' },
{ id: 2, name: 'Shyam' },
{ id: 1, name: 'Ram' },
{ id: 3, name: 'Sita' },
];
// Adding values of id key of each object to set
const mySet = new Set(persons.map((person) => person.id));
// Converting Set to a array using Array.from() method
const uniqueIds = Array.from(mySet);
console.log(uniqueIds);
Output:
[1, 2, 3]
3.Using reduce() method
This approach uses the reduce() method to build a new array containing only the unique objects. For each object in the input array, it checks if the unique array already contains an object with the same key value. If not, it adds the object to the unique array.
Example: The below code explains the use of reduce() method to remove duplicate objects.
JavaScript
function removeDuplicates(
arr: any[],
key: string
): any[] {
return arr.reduce((unique, item) => {
// Check if the current object has the specified key
if (item.hasOwnProperty(key)) {
// Check if there is no existing object with the same key value
if (
!unique.some(
(obj) =>
obj[key] === item[key]
)
) {
unique.push(item);
}
} else {
// If the key doesn't exist in the current object, always include it in the unique array
unique.push(item);
}
return unique;
}, []);
}
let arrayOfObjects = [
{ id: 1, name: "amit" },
{ id: 2, name: "saurabh" },
{ id: 1, name: "amit" },
{ id: 3, name: "soham" },
{ id: 2, name: "saurabh" },
];
let uniqueArray = removeDuplicates(
arrayOfObjects,
"id"
);
console.log(uniqueArray);
Output
[
{ id: 1, name: 'amit' },
{ id: 2, name: 'saurabh' },
{ id: 3, name: 'soham' }
]
4. Using an Object to Track Unique Objects
This approach involves using an object to keep track of unique objects based on a specific property. It iterates through the array of objects, and for each object, it checks whether the property value already exists in the object. If it does not exist, it adds the object to the result array and adds the property value to the tracking object. This approach ensures that only unique objects are included in the result.
Syntax:
function removeDuplicates(arr: any[], key: string): any[] {
return arr.reduce((unique, item) => {
if (!unique.find(obj => obj[key] === item[key])) {
unique.push(item);
}
return unique;
}, []);
}
Example: The following code demonstrates the use of the removeDuplicates function to remove duplicate objects based on the id property from an array of objects.
JavaScript
function removeDuplicates(arr: any[], key: string): any[] {
return arr.reduce((unique, item) => {
if (!unique.find((obj : any) => obj[key] === item[key])) {
unique.push(item);
}
return unique;
}, []);
}
interface Person {
id: number;
name: string;
}
const arrayOfObjects: Person[] = [
{ id: 1, name: "nikunj" },
{ id: 2, name: "dhruv" },
{ id: 1, name: "nikunj" },
{ id: 3, name: "yash" },
{ id: 2, name: "dhruv" },
];
const uniqueArray = removeDuplicates(arrayOfObjects, "id");
console.log(uniqueArray);
Output:
[{
"id": 1,
"name": "nikunj"
}, {
"id": 2,
"name": "dhruv"
}, {
"id": 3,
"name": "yash"
}]
Similar Reads
How to Remove Duplicates from an Array of Objects in JavaScript?
Here are some effective methods to remove duplicates from an array of objects in JavaScript 1. Using filter() and findIndex() Methods - Most UsedThe simplest way to remove duplicates is by using filter() and findIndex(). This method keeps the first occurrence of each object with a unique property (l
3 min read
How to Remove Duplicate Elements from an Array using Lodash ?
Removing duplicate elements from an array is necessary for data integrity and efficient processing. The approaches implemented and explained below will use the Lodash to remove duplicate elements from an array. Table of Content Using uniq methodUsing groupBy and map methodsUsing xor functionUsing un
3 min read
How to move Duplicate to First Index in an Array of Objects in TypeScript ?
To efficiently rearrange an array of objects in TypeScript, moving duplicates to the first index, The approach is first to identify the duplicate within the array, then to remove the duplicate from its current position in the array then at last to re-insert the duplicate at the first index of the ar
7 min read
How to Remove Duplicate Objects from an Array in JavaScript?
In JavaScript, it's a common example that the arrays contain objects and there might be a possibility that the objects may or may not be unique. Removing these duplicate objects from the array and getting the unique ones is a common task in Web Development. These are the following approaches: Table
2 min read
How to get Function Parameters from Keys in an Array of Objects Using TypeScript ?
In TypeScript, we can extract the function parameters from keys in an array of objects by going through object properties dynamically. We can use Generics and Type Assertion to get Function Parameters from Keys in an Array of Objects Using TypeScript. Below are the possible approaches: Table of Cont
3 min read
Remove Duplicate Elements from TypeScript Array
TypeScript array is a single variable that is used to store the elements or a group of values of the same type. An array can contain multiple occurrences or duplicates of an element that can be removed using the below-discussed methods. Below are the approaches used to remove Duplicate Elements from
5 min read
How to Sort an Array of Object using a Value in TypeScript ?
Sorting an array of objects using a value in TypeScript pertains to the process of arranging an array of objects in a specified order based on a particular property or value contained within each object. The below approaches can be used to sort an array of objects using a value in TypeScript: Table
3 min read
How to Create a Typed Array from an Object with Keys in TypeScript?
Creating a typed array from the keys of an object in TypeScript ensures that your application maintains type safety, particularly when interacting with object properties. Here we'll explore different approaches to achieve this using TypeScript's built-in Object methods. Below are the approaches used
3 min read
How to Create a Union Type from Nested Array in TypeScript ?
TypeScript developers often encounter scenarios where they need to represent a value that could be one of several different types. TypeScript's union types provide a solution to this problem by allowing variables to hold values of multiple types. However, when dealing with nested arrays, each nested
3 min read
How to Remove Keys from a TypeScript Dictionary ?
In TypeScript, we can remove keys from a TypeScript Dictionary using various approaches that include deleting keywords, Object Destructuring, and by using Object.keys() and Array.reduce() methods. There are several approaches to removing keys from a TypeScript Dictionary which are as follows: Table
3 min read