Skip to content
Related Articles

Related Articles

Improve Article

Extract unique objects by attribute from array of objects.

  • Last Updated : 14 Feb, 2019

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)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :