JavaScript - How To Get Distinct Values From an Array of Objects?
Last Updated :
27 Nov, 2024
Here are the different ways to get distinct values from an array of objects in JavaScript
1. Using map() and filter() Methods
This approach is simple and effective for filtering distinct values from an array of objects. You can use map() to extract the property you want to check for uniqueness, and then apply filter() to keep only the first occurrence.
JavaScript
const a = [
{ id: 1, name: "Rahul" },
{ id: 2, name: "Priya" },
{ id: 1, name: "Rahul" },
{ id: 3, name: "Amit" }
];
const dist = a.filter((obj, index, self) =>
index === self.findIndex((t) => t.id === obj.id)
);
console.log(dist);
Output[
{ id: 1, name: 'Rahul' },
{ id: 2, name: 'Priya' },
{ id: 3, name: 'Amit' }
]
2. Using Set() Constructor
The Set() constructor allows you to create a collection of unique values. You can use it to remove duplicates from an array of objects by converting the objects into a unique string representation (such as a JSON string).
JavaScript
const a = [
{ id: 1, name: "Rahul" },
{ id: 2, name: "Priya" },
{ id: 1, name: "Rahul" },
{ id: 3, name: "Amit" }
];
const dist = Array.from(new Set(a.map(obj => JSON.stringify(obj))))
.map(e => JSON.parse(e));
console.log(dist);
Output[
{ id: 1, name: 'Rahul' },
{ id: 2, name: 'Priya' },
{ id: 3, name: 'Amit' }
]
3. Using map(), set() and from() Methods
You can combine map(), Set(), and Array.from() to get distinct values based on a specific property. This method ensures uniqueness while keeping your code concise.
JavaScript
const a = [
{ id: 1, name: "Rahul" },
{ id: 2, name: "Priya" },
{ id: 1, name: "Rahul" },
{ id: 3, name: "Amit" }
];
const dist = Array.from(new Set(a.map(obj => obj.id)))
.map(id => a.find(obj => obj.id === id));
console.log(dist);
Output[
{ id: 1, name: 'Rahul' },
{ id: 2, name: 'Priya' },
{ id: 3, name: 'Amit' }
]
4. Using Lodash _.uniqBy() method and map()
Lodash provides the uniqBy() method, which is specifically designed to remove duplicates from an array of objects based on a specific property.
JavaScript
const _ = require('lodash');
const a = [
{ id: 1, name: "Rahul" },
{ id: 2, name: "Priya" },
{ id: 1, name: "Rahul" },
{ id: 3, name: "Amit" }
];
const dist = _.uniqBy(a, 'id');
console.log(dist);
Output
[
{ id: 1, name: 'Rahul' },
{ id: 2, name: 'Priya' },
{ id: 3, name: 'Amit' }
]
5. Using reduce() Method
The reduce() method allows you to accumulate distinct objects into an array by checking if the object’s property already exists in the result array.
JavaScript
const a = [
{ id: 1, name: "Rahul" },
{ id: 2, name: "Priya" },
{ id: 1, name: "Rahul" },
{ id: 3, name: "Amit" }
];
const dist = a.reduce((acc, obj) => {
if (!acc.some(item => item.id === obj.id)) {
acc.push(obj);
}
return acc;
}, []);
console.log(dist);
Output[
{ id: 1, name: 'Rahul' },
{ id: 2, name: 'Priya' },
{ id: 3, name: 'Amit' }
]
6. Using filter() and indexOf()
This method uses filter() to iterate over the array and indexOf() to check if the object has already appeared in the array.
JavaScript
const a = [
{ id: 1, name: "Rahul" },
{ id: 2, name: "Priya" },
{ id: 1, name: "Rahul" },
{ id: 3, name: "Amit" }
];
const dist = a.filter((obj, index, self) =>
index === self.findIndex((t) => t.id === obj.id)
);
console.log(dist);
Output[
{ id: 1, name: 'Rahul' },
{ id: 2, name: 'Priya' },
{ id: 3, name: 'Amit' }
]
7. Using Array.prototype.forEach() and a temporary object
Using a temporary object allows you to track unique properties manually during iteration.
JavaScript
const a = [
{ id: 1, name: "Rahul" },
{ id: 2, name: "Priya" },
{ id: 1, name: "Rahul" },
{ id: 3, name: "Amit" }
];
const seen = {};
const dist = [];
a.forEach((obj) => {
if (!seen[obj.id]) {
dist.push(obj);
seen[obj.id] = true;
}
});
console.log(dist);
Output[
{ id: 1, name: 'Rahul' },
{ id: 2, name: 'Priya' },
{ id: 3, name: 'Amit' }
]
8. Using reduce() and Object.values()
You can also combine reduce() with Object.values() to remove duplicates by ensuring that only the first occurrence of each property is kept.
JavaScript
const a = [
{ id: 1, name: "Rahul" },
{ id: 2, name: "Priya" },
{ id: 1, name: "Rahul" },
{ id: 3, name: "Amit" }
];
const dist = Object.values(a.reduce((acc, obj) => {
acc[obj.id] = obj;
return acc;
}, {}));
console.log(dist);
Output[
{ id: 1, name: 'Rahul' },
{ id: 2, name: 'Priya' },
{ id: 3, name: 'Amit' }
]
Similar Reads
How to Remove Duplicates from an Array of Objects in JavaScript?
Here are some effective methods to remove duplicates from an array of objects in JavaScript1. Using filter() and findIndex() Methods - Most UsedThe simplest way to remove duplicates is by using filter() and findIndex(). This method keeps the first occurrence of each object with a unique property (li
3 min read
How to Remove Duplicate Objects from an Array in JavaScript?
In JavaScript, it's a common example that the arrays contain objects and there might be a possibility that the objects may or may not be unique. Removing these duplicate objects from the array and getting the unique ones is a common task in Web Development. These are the following approaches: Table
2 min read
How to convert a map to array of objects in JavaScript?
A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys. Let us discuss some methods
6 min read
How to compare Arrays of Objects in JavaScript?
In JavaScript, comparing arrays of objects can be more complex than comparing primitive data types. We will discuss different ways to compare arrays of objects effectively, with detailed code examples and explanations.Syntax: Before going to detail the comparison techniques, let's first understand h
5 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 thro
5 min read
JavaScript Get all non-unique values from an array
We have given a JavaScript array, and the task is to find all non-unique elements of the array. To get all non-unique values from the array here are a few examples. These are the following methods to get all non-unique values from an array:Table of ContentUsing Array Slice() MethodUsing for loopUsin
4 min read
How to remove given object from an Array in Java?
Given an array arr of N objects, the task is to remove all the occurrences of a given object from the array in Java. Example: Input: String[] arr = { "Geeks", "for", "Geeks", "hello", "world" }, removeObj = "Geeks" Output: updated arr[] = {"for", "hello", "world"}Explanation: All the occurrences of
3 min read
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 v
8 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 JavaScriptExample:Input:[ { apple: 2, mango: 4, }, { apple: 3, mango: 6, }, { apple: 7, mango: 11, },]Outp
3 min read
How to Convert Array into Array of Objects using map() & reduce() in JavaScript?
An array of objects can contain multiple objects with the same properties i.e. key-value pairs. But a map does not contain duplicate values which means if you convert an array of objects with duplicate objects into a map, it will contain only the unique key-value pairs. Below are the approaches to c
2 min read