![]() |
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 TypeScriptTable of Content 1.Using filter() and findIndex() methodsThis 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.
Output: [
{ "id": 1, "name": "Ram" },
{ "id": 2, "name": "Shyam" },
{ "id": 3, "name": "Sita" }
] 2.Using Set and Array.from() methodThis 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.
Output: [1, 2, 3] 3.Using reduce() methodThis 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.
Output[
{ id: 1, name: 'amit' },
{ id: 2, name: 'saurabh' },
{ id: 3, name: 'soham' }
] 4. Using an Object to Track Unique ObjectsThis 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.
Output: [{
"id": 1,
"name": "nikunj"
}, {
"id": 2,
"name": "dhruv"
}, {
"id": 3,
"name": "yash"
}] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |