Extract unique objects by attribute from an array of objects in JavaScript


We will learn to extract unique objects by attribute from an array of objects in this tutorial. Sometimes, we need to filter objects from the array of objects based on a particular attribute.

For example, we have an id as a key to identify the object. So, we need to ensure that the array contains only a single object with a single id. If two or more objects contain the same primary key value, it can cause the problem of uniquely identifying objects.

Here, we will learn different approaches to filter all unique objects from the array based on a particular attribute.

Using the Map and for Loop

In JavaScript, Map can store the unique key-value pairs. Also, we can get any value from the Map using its key in the O(1) time complexity. So, we will iterate through the objects array and store the key-value pairs in the Map. Also, we will check if Map contains the object with the particular attribute value; we will not add that object to the new object’s array.

Syntax

You can follow the syntax below to extract the unique objects from the array using the map.

const employees = [
   { emp_id: 1, emp_name: "Shubham", emp_age: 22 },
   { emp_id: 1, emp_name: "Joe", emp_age: 23 },
];     
var map = new Map();
for (let employee of employees) {
   map.set(employee["emp_id"], employee);
}
var iteratorValues = map.values();
var uniqueEmployess = [...iteratorValues];

In the above syntax, we have used the map to store the objects with unique emp_id.

Algorithm

  • Step 1 − Create an objects array that contains multiple objects with duplicate emp_id.

  • Step 2 − Create a Map() object using the Map constructor.

  • Step 3 − Use the for-of loop to iterate through every object of the ‘employees’ array.

  • Step 4 − For the map, use the emp_id as a key and the whole object as a value. In the for-of loop, use the set() method of the Map object to set the object as a value for the emp_id key.

  • Step 5 − The map is an iterator. So, to get all values of an iterator, apply the values() method.

  • Step 6 − Use the spread operator to copy all objects from the iteratorValues to the uniqueEmployees array.

  • Step 7 − The uniqueEmployees array contains all objects with unique emp_id, and users can iterate through it to get object values.

Example

In the example below, we have implemented the algorithm to extract the unique objects by attribute using the Map and for-of loop. We have created the employees' array, which contains the four different objects with duplicate emp_id values, and we are using the above algorithm to extract all the unique objects.

<html>
<body>
   <h3>Extracting the unique objects by the emp_id attribute of an array of objects using the <i> Map and for-loop. </i></h3>
   <div id="output"></div>
   <script>
      let output = document.getElementById("output");
      // creating the array of employees, which contains multiple objects.
      const employees = [
         { emp_id: 1, emp_name: "Shubham", emp_age: 22 },
         { emp_id: 2, emp_name: "Joe", emp_age: 23 },
         { emp_id: 2, emp_name: "Sam", emp_age: 62 },
      ];
      var map = new Map();
      for (let employee of employees) {
         // setting up the employee object for unique emp_id value
         map.set(employee["emp_id"], employee);
      }
      var iteratorValues = map.values();
      var uniqueEmployess = [...iteratorValues];
      for (let uniqueEmp of uniqueEmployess) {
         output.innerHTML += "The new unique object values is </br>";
         output.innerHTML +=  "emp_id :- " + uniqueEmp.emp_id +
            ", emp_name :-  " + uniqueEmp.emp_name +
            ", emp_age :- " + uniqueEmp.emp_age +" </br> ";
      }
   </script>
</body>
</html>

Use the array.filter() method and Map

We can use the filter() method to filter the values from the array. It takes the callback function as a parameter and filters values based on the returned boolean value from the callback function.

Like the above example, we will use the map to store attribute values and check if the map already contains that value. If so, we will move ahead; otherwise, we will add those values to the map and filtered array.

Syntax

Users can follow the syntax below to filter all objects with the unique attribute value.

var map = new Map();
let uniqueObjects = websites.filter((web) => {
   if (map.get(web.website_name)) {
      return false;
   }
   map.set(web.website_name, web);
   return true;
});

Algorithm

  • Step 1 − Create a map using the Map() object.

  • Step 2 − Use the filter() method to filter values from the array.

  • Step 3 − Pass the callback function as a parameter of the filter method, which takes the web as a parameter. The web is an object from the reference array.

  • Step 4 − Check if the map already contains the website_name as a key, and move ahead by returning false from the callback function.

  • Step 5 − If the map doesn’t contain the website_name, add website_name and object as a key-value pair in the map and return true to filter it out in the uniqueObjects array.

Example

In this example, we have used the filter() method to filter all website objects by website_name from the array. In the output, users can observe that the filter() method returns only two objects containing the unique website_name.

<html>
<body>
   <h3>Extracting the unique objects by the website_name attribute of an array of objects using the <i> Map and filter() method. </i></h3>
   <div id="output"></div>
   <script>
      let output = document.getElementById("output");
         //creating the array of websites object. A single website can have multiple domains
      const websites = [
         { website_name: "TutorialsPoint", domain: "tutorialspoint.com" },
         { website_name: "TutorialsPoint", domain: "qries.com" },
         { website_name: "Tutorix", domain: "tutorix.com" },
      ];
      var map = new Map();
      let uniqueObjects = websites.filter((web) => {
         if (map.get(web.website_name)) {
            return false;
         }
         // If website_name is not found in the map, return true.
         map.set(web.website_name, web);
         return true;
      });
      // iterating through the unique objects and printing its value
      for (let web of uniqueObjects) {
         output.innerHTML += "The new unique object values is </br>";
         output.innerHTML += "website_name :- " + web.website_name +
            ", domain :-  " +  web.domain +  " </br> ";
     }
   </script>
</body>
</html>

This tutorial taught us two approaches to extracting unique objects by particular attribute values. We used the map in both approaches but have used different iterator methods to iterate through the object’s array. Users can use the for-of loop or filter() method to iterate through the array.

Updated on: 17-Jan-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements