Open In App

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

In this article, we will try to understand 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.

These are the following ways to solve this problem:



Approach 1: Using map() and filter() Methods

Example: Below is the implementation of the above approach.




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: Use Set() Constructor

Example: Below is the implementation of the above approach.




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 ]

Approach 3: Using map(), set() and from() Methods

Example:




let employees_details = [
    { name: "Ram", age: 17 },
    { name: "Shyam", age: 17 },
    { name: "Mohan", age: 30 },
];
 
const propertyValues =
      employees_details.map(obj => obj['name']);
const uniqueValuesSet =
      new Set(propertyValues);
const distinctValues =
       Array.from(uniqueValuesSet);
console.log(distinctValues);

Output
[ 'Ram', 'Shyam', 'Mohan' ]

Approach 4: Using Lodash _.uniqBy() method and map()

In this approach, we are using the Lodash _.uniqBy() method which returns the unique value of age and we are getting the values of age by the use of map() method in JavaScript.

Example: This example shows the implementation of above-explained approach.




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let y = [
    { name: "Ram", age: 17 },
    { name: "Shyam", age: 17 },
    { name: "Mohan", age: 30 },
];
 
// Extracting unique values of 'age' property
let uniqueAges = _.uniq((y, 'age'));
let result = uniqueAges.map(obj => obj['age']);
 
// Printing the output
console.log(result);

Output:

[17,30]

Article Tags :