Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to get distinct values from an array of objects in JavaScript?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In this article, we will try to understand that how we may get distinct values from an array of objects in JavaScript with the help of certain examples.

Pre-requisite: Array of Objects in JavaScript

Example:

Input:
[
    { name: "Ram", age: 17 },
    { name: "Shyam", age: 17 },
    { name: "Mohan", age: 30 },
]
Output: [17, 30]

Explanation:

  • From the input, which is the array of objects, select any key that might contain duplicate values in or as another object’s key.
  • Select distinct values of the same key from different objects present in the array itself.

After understanding the desired task from the above example, let us quickly see the following approaches through which we may understand as well as solve solutions for the above-shown task.

Approach 1:

  • In this approach, we will use several functions, including map() and filter() methods inside our helper method that contains an array of objects as our parameter.
  • Using the map() method we will iterate over an array of objects and using the filter() method we will filter out the values which are not duplicate.

Example: Below is the implementation of the above approach.

Javascript




let employees_details = [
    { name: "Ram", age: 17 },
    { name: "Shyam", age: 17 },
    { name: "Mohan", age: 30 },
];
  
let desired_output = (employees_details) => {
    let unique_values = employees_details
        .map((item) => item.age)
        .filter(
            (value, index, current_value) => current_value.indexOf(value) === index
        );
    return unique_values;
};
  
console.log(desired_output(employees_details));

Output:

[ 17, 30 ]

Approach 2:

  • In this approach, we will use Set() provided in JavaScript which will help us to store non-duplicate values.
  • After storing non-duplicated values, we will return those values in the form of an array as an output.

Example: Below is the implementation of the above approach.

Javascript




let employees_details = [
    { name: "Ram", age: 17 },
    { name: "Shyam", age: 17 },
    { name: "Mohan", age: 30 },
];
  
let desired_output = (employees_details) => {
    let unique_values = [
        ...new Set(employees_details.map((element) => element.age)),
    ];
    return unique_values;
};
  
console.log(desired_output(employees_details));

Output:

[ 17, 30 ]

My Personal Notes arrow_drop_up
Last Updated : 25 Jan, 2023
Like Article
Save Article
Similar Reads
Related Tutorials