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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output:

[ { name: 'Geeks', id: 10 }, 
  { name: 'GeeksForGeeks', id: 10 } ]

Time Complexity: O(n)
Space Complexity: O(n)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.