The Wayback Machine - https://web.archive.org/web/20240718030020/https://www.geeksforgeeks.org/extract-unique-objects-by-attribute-from-array-of-objects/
Open In App

Extract unique objects by attribute from array of objects

Last Updated : 21 Apr, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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.

C++
#include <iostream>
#include <vector>
#include <unordered_map>

struct Object {
    std::string name;
    int id;
};

int main() {
    std::vector<Object> objects = {
        {"Geeks", 10},
        {"GeeksForGeeks", 10},
        {"Geeks", 20},
        {"Geeks", 10}
    };

    std::unordered_map<std::string, int> mymap;
    std::vector<Object> unique;

    for (const auto& el : objects) {
        if (mymap.find(el.name) != mymap.end()) {
            if (el.id < mymap[el.name]) {
                mymap[el.name] = el.id;
                unique.push_back(el);
            }
        } else {
            mymap[el.name] = el.id;
            unique.push_back(el);
        }
    }

    for (const auto& obj : unique) {
        std::cout << "Name: " << obj.name << ", ID: " << obj.id << std::endl;
    }

    return 0;
}
Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UniqueObjectsFilter {
    public static void main(String[] args) {
        // Given objects array
        List<Map<String, Object>> objects = new ArrayList<>();
        objects.add(Map.of("name", "Geeks", "id", 10));
        objects.add(Map.of("name", "GeeksForGeeks", "id", 10));
        objects.add(Map.of("name", "Geeks", "id", 20));
        objects.add(Map.of("name", "Geeks", "id", 10));

        // Initialize a map to store the minimum 'id' for each 'name'
        Map<String, Integer> myMap = new HashMap<>();

        // Initialize a list to store unique objects
        List<Map<String, Object>> unique = new ArrayList<>();

        // Loop through each object in the 'objects' list
        for (Map<String, Object> el : objects) {
            // Check if 'name' is already in the map
            if (myMap.containsKey(el.get("name"))) {
                // If yes, compare the current 'id' with the stored minimum 'id'
                if ((int) el.get("id") < myMap.get(el.get("name"))) {
                    // If the current 'id' is smaller, update the minimum 'id' in the map
                    myMap.put((String) el.get("name"), (int) el.get("id"));
                    // Add the current object to the list of unique objects
                    unique.add(el);
                }
            } else {
                // If 'name' is not in the map, add it with the current 'id'
                myMap.put((String) el.get("name"), (int) el.get("id"));
                // Add the current object to the list of unique objects
                unique.add(el);
            }
        }

        // Print the list of unique objects
        System.out.println(unique);
    }
}
Python3
# Given JavaScript code to filter unique objects based on 'name' with the minimum 'id'
objects = [
    {"name": "Geeks", "id": 10},
    {"name": "GeeksForGeeks", "id": 10},
    {"name": "Geeks", "id": 20},
    {"name": "Geeks", "id": 10}
]

# Initialize an empty dictionary to store the minimum 'id' for each 'name'
mymap = {}

# Initialize an empty list to store unique objects
unique = []

# Loop through each object in the 'objects' array
for el in objects:
    # Check if 'name' is already in the dictionary
    if el["name"] in mymap:
        # If yes, compare the current 'id' with the stored minimum 'id'
        if el["id"] < mymap[el["name"]]:
            # If the current 'id' is smaller, update the minimum 'id' in the dictionary
            mymap[el["name"]] = el["id"]
            # Add the current object to the list of unique objects
            unique.append(el)
    else:
        # If 'name' is not in the dictionary, add it with the current 'id'
        mymap[el["name"]] = el["id"]
        # Add the current object to the list of unique objects
        unique.append(el)

# Print the list of unique objects
print(unique)
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 } ]



Similar Reads

How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Arrays of objects are a common data structure in JavaScript, often used to store and manipulate collections of related data. However, there are scenarios where you may need to convert an array of objects into a unique array, removing any duplicate objects based on specific criteria. JavaScript has various methods to convert an array of objects into
6 min read
How to extract value of a property as array from an array of objects ?
We will try to understand that how we may extract the value of a property as an array from an array of objects in JavaScript with the help of certain examples. Pre-requisite: Array of Objects in JavaScript Example: Input:[ { apple: 2, mango: 4, }, { apple: 3, mango: 6, }, { apple: 7, mango: 11, },]Output: [2, 3, 7]Explanation: From an array contain
4 min read
Filter Array of Objects with Another Array of Objects in JavaScript
Filtering an array of objects with another array in JavaScript involves comparing and including objects based on specific criteria. Below are the approaches to filter an array of objects with another array of objects in JavaScript: Table of Content Using filter and includes MethodsUsing LoopingUsing reduce MethodUsing filter and includes MethodsIn
3 min read
How to Update an Array of Objects with Another Array of Objects using Lodash?
Updating an array of objects with another array of objects involves merging or updating objects in the first array with corresponding objects from the second array. Below are the approaches to update an array of objects with another array of objects in the Lodash library: Table of Content Using _.merge function from lodashUsing _.mergeWith function
2 min read
How to Return an Array of Unique Objects in JavaScript ?
Returning an array of unique objects consists of creating a new array that contains unique elements from an original array. We have been given an array of objects, our task is to extract or return an array that consists of unique objects using JavaScript approaches. There are various approaches through which it can be performed which are as follows
5 min read
How to Separate Array of Objects into Multiple Objects in JavaScript ?
In JavaScript, the task of separating an array of objects into multiple objects involves organizing and restructuring data based on specific criteria or properties. This process is often necessary when dealing with datasets that need to be grouped or segmented for easier analysis or manipulation. There are various methods to achieve this separation
4 min read
How to Remove Multiple Objects from Nested Array of Objects in JavaScript ?
A nested array of objects is an array of arrays that contain multiple objects as their elements. Removing multiple objects from the nested array of objects in JavaSript can be accomplished in different ways as listed below: Table of Content Using filter() with some() methodUsing filter() with includes() methodUsing filter( ) with findIndex() method
6 min read
How to Remove Null Objects from Nested Array of objects in JavaScript ?
Removing null objects from the nested array of objects can be done by iterating over the array, filtering out the null objects at each level, and then applying a recursive approach to remove all the null objects. This makes sure that all the levels of the nested structure are checked and the null objects are removed. There are various approaches to
7 min read
How to Convert Object Containing Objects into Array of Objects using Lodash?
Lodash is a JavaScript utility library that provides predefined functions to make code more readable and cleaner. These functions are optimized for performance, often being faster than native JavaScript methods for complex operations.We will learn how to convert an object containing objects into an array of objects using Lodash. There are two appro
2 min read
Max/Min value of an attribute in an array of objects in JavaScript
In this article, we are given an array of objects and the task is to get the maximum and minimum values from the array of objects. For this approach, we have a few methods that will be discussed below. Methods to get Min/Max values:using JavaScript apply() and Array map()using JavaScript Array reduce() Methodusing JavaScript loopsMethod 1: Using Ja
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg