Extract unique objects by attribute from array of objects.
Given an array of objects and the task is to return the unique object by the attribute.
Examples:
Input:
[ { name: 'Geeks', id: 10 },
{ name: 'GeeksForGeeks', id: 10 },
{ name: 'Geeks', id: 20 },
{ name: 'Geeks', id: 10 } ]
Output:
[ { name: 'Geeks', id: 10 },
{ name: 'GeeksForGeeks', id: 10 } ]
Approach: Let’s assume that name as attribute that differentiate the objects and need the object with minimum id number if multiple objects exists for same name. Use the map to store objects and check whether similar object seen or not.
- Initialize an empty map.
- Iterate through array using filter method.
- Check if there is any entry in map with same name as of current object.
- —-If true: i.e. there exists an entry with same name then, check if its id is less than current object’s id.
- ——–If true: i.e current object’s id is less than the id of the object returned by map then delete the map entry and enter the current object and return true.
- ——–if false: i.e. id of current object is greater than the id of object returned by map then return false.
- —-If false: i.e. there is no entry in map with same name then enter the current object into map.
- Print unique objects.
Example:
<script> objects = [{ name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 }, { name: 'Geeks', id: 20 }, { name: 'Geeks', id: 10 }]; let mymap = new Map(); unique = objects.filter(el => { const val = mymap.get(el.name); if(val) { if(el.id < val) { mymap.delete(el.name); mymap.set(el.name, el.id); return true; } else { return false; } } mymap.set(el.name, el.id); return true; }); console.log(unique); </script> |
Output:
[ { name: 'Geeks', id: 10 },
{ name: 'GeeksForGeeks', id: 10 } ]
Time Complexity: O(n)
Space Complexity: O(n)
Recommended Posts:
- Max/Min value of an attribute in an array of objects in JavaScript
- Sort array of objects by object fields in PHP
- How to remove duplicates from an array of objects using JavaScript ?
- How to remove Objects from Associative Array in JavaScript ?
- JavaScript | length of string and array objects
- Sort array of objects by string property value in JavaScript
- How to compare two JavaScript array objects using jQuery/JavaScript ?
- PHP | Objects
- How to merge two PHP objects?
- Objects in Javascript
- JavaScript | Objects
- JavaScript | Date Objects
- Bootstrap 4 | Media Objects
- Creating objects in JavaScript (3 Different Ways)
- Media Objects in Bootstrap with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



