Friday, December 27, 2024
Google search engine
HomeLanguagesJavascriptExtract unique objects by attribute from array of objects

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 is an attribute that differentiates the objects and needs the object with a minimum id number if multiple objects exist for the same name. Use the map to store objects and check whether similar objects were seen or not.

  • Initialize an empty map.
  • Iterate through the array using the filter() method.
  • Check if there is any entry in the map with the same name as of current object.
    • If true: i.e. there exists an entry with the same name then, check if its id is less than the current object’s id.
      • If true: i.e current object’s id is less than the id of the object returned by the map then delete the map entry and enter the current object and return true.
      • if false: i.e. id of the current object is greater than the id of the object returned by the map then return false.
    • If false: i.e. there is no entry in a map with the same name then enter the current object into the map.
  • Print unique objects.

Example: In this example, we will extract unique objects by attribute from an array of objects.

javascript




let objects = [{
    name: 'Geeks',
    id: 10
}, {
    name: 'GeeksForGeeks',
    id: 10
}, {
    name: 'Geeks',
    id: 20
}, {
    name: 'Geeks',
    id: 10
}];
 
let mymap = new Map();
 
let 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);


Output

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments