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:
- Sort array of objects by object fields in PHP
- JavaScript | length of string and array objects
- PHP | Objects
- How to merge two PHP objects?
- Objects in Javascript
- JavaScript | Objects
- Creating objects in JavaScript (3 Different Ways)
- Media Objects in Bootstrap with Examples
- How to evenly put N objects into N places with adjacent moves
- Find Sum of all unique sub-array sum for a given array.
- Number of unique pairs in an array
- Unique element in an array where all elements occur k times except one
- Minimum Increment operations to make Array unique
- Find Unique pair in an array with pairs of numbers
- Maximum possible sum of a window in an array such that elements of same window in other array are unique
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.



