How to Return an Array of Unique Objects in JavaScript ?
Last Updated :
17 Jun, 2024
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:
Using Set
This method uses Set to extract unique objects by first converting each of the objects into the JSON string, then mapping it back to the objects. The output array contains the unique objects.
Syntax:
let mySet = new Set([iterable]);
Example: The below code uses a set to return an array of unique objects.
JavaScript
// input arr
let arr = [
{ articleId: 101, title: "Introduction to JavaScript" },
{ articleId: 102, title: "Arrays in JavaScript" },
{ articleId: 101, title: "Introduction to JavaScript" },
{ articleId: 103, title: "Functions in JavaScript" },
];
// Set to get unique objects
let setObj = new Set(arr.map(JSON.stringify));
let output = Array.from(setObj).map(JSON.parse);
// Output
console.log(output);
Output[
{ articleId: 101, title: 'Introduction to JavaScript' },
{ articleId: 102, title: 'Arrays in JavaScript' },
{ articleId: 103, title: 'Functions in JavaScript' }
]
Using filter Method
This method uses the filter method in JavaScript to return only the first occurrence of each unique object in the input array, using JSON.stringify for the comparison. The output array has the unique objects stored.
Syntax:
let newArray = array.filter(callback(element, index, array));
Example: The below code uses filter and indexOf methods to return an array of unique objects.
JavaScript
// Input arr
let arr = [
{ articleId: 101, title: 'Introduction to JavaScript' },
{ articleId: 102, title: 'Arrays in JavaScript' },
{ articleId: 101, title: 'Introduction to JavaScript' },
{ articleId: 103, title: 'Functions in JavaScript' }
];
// Filter and indexOf to get unique objects
let output = arr.filter(
(obj, index, arr) =>
{
return arr.findIndex(o =>
{
return JSON.stringify(o) === JSON.stringify(obj)
}) === index
}
);
// Output
console.log(output);
Output[
{ articleId: 101, title: 'Introduction to JavaScript' },
{ articleId: 102, title: 'Arrays in JavaScript' },
{ articleId: 103, title: 'Functions in JavaScript' }
]
Using reduce Method
The method uses the reduce method from JavaScript to accumulate unique objects from the input array by checking for the existing objects using JSON.stringify. The output array stores the unique objects and is printed using the log() function.
Syntax:
let result = array.reduce(callback(accumulator, currentValue, index, array), initialValue);
Example: The below code uses the reduce method to return an array of unique objects.
JavaScript
// Input arr
let arr = [
{ articleId: 101, title: "Introduction to JavaScript" },
{ articleId: 102, title: "Arrays in JavaScript" },
{ articleId: 101, title: "Introduction to JavaScript" },
{ articleId: 103, title: "Functions in JavaScript" },
];
// Reduce method to get unique objects
let output = arr.reduce((acc, obj) => {
if (!acc.some(o => o.articleId === obj.articleId)) {
acc.push(obj);
}
return acc;
}, []);
// Output
console.log(output);
Output[
{ articleId: 101, title: 'Introduction to JavaScript' },
{ articleId: 102, title: 'Arrays in JavaScript' },
{ articleId: 103, title: 'Functions in JavaScript' }
]
We use the some method to check if the current object's articleId already exists in the accumulator. And If the articleId is not found in the accumulator, we push the current object obj into the accumulator. Thus accumulator acc contains only unique objects based on the articleId
Using map Method
This method uses the map method along with callback to get unique objects by associating each object with the JSON string. The output array consists of unique objects and is printed using the log() function.
Syntax:
let newArray = array.map(callback(currentValue, index, array));
Example: The below code uses the map method to return an array of unique objects.
JavaScript
// input arr
let arr = [
{ articleId: 101, title: "Introduction to JavaScript" },
{ articleId: 102, title: "Arrays in JavaScript" },
{ articleId: 101, title: "Introduction to JavaScript" },
{ articleId: 103, title: "Functions in JavaScript" },
];
// Map method to get unique objects
let mapObj = new Map(
arr.map((obj) => {
return [JSON.stringify(obj), obj];
})
);
let output = Array.from(mapObj.values());
// Output
console.log(output);
Output[
{ articleId: 101, title: 'Introduction to JavaScript' },
{ articleId: 102, title: 'Arrays in JavaScript' },
{ articleId: 103, title: 'Functions in JavaScript' }
]
Using Object Key for Tracking Unique Objects
This method uses an object to track and store unique objects based on a specified attribute. The keys of the object are the values of the specified attribute, ensuring uniqueness.
Syntax:
let newArray = array.reduce((acc, current) => {
// logic to track unique objects
return acc;
}, {});
Example:
JavaScript
// Input array
let arr = [
{ articleId: 101, title: "Introduction to JavaScript" },
{ articleId: 102, title: "Arrays in JavaScript" },
{ articleId: 101, title: "Introduction to JavaScript" },
{ articleId: 103, title: "Functions in JavaScript" },
];
// Using an object key to track unique objects
let uniqueObjects = {};
arr.forEach(obj => {
uniqueObjects[obj.articleId] = obj;
});
let output = Object.values(uniqueObjects);
// Output
console.log(output);
// Nikunj Sonigara
Output[
{ articleId: 101, title: 'Introduction to JavaScript' },
{ articleId: 102, title: 'Arrays in JavaScript' },
{ articleId: 103, title: 'Functions in JavaScript' }
]
Similar Reads
How to Access Array of Objects in JavaScript ? Accessing an array of objects in JavaScript is a common task that involves retrieving and manipulating data stored within each object. This is essential when working with structured data, allowing developers to easily extract, update, or process information from multiple objects within an array.How
4 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 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 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 read properties of an Object in JavaScript ? Objects in JavaScript, it is the most important data type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScriptâs primitive data-types(Number, String, Boolean, null, undefined, and symbol) in the sense that these primitive data-types all store a singl
2 min read
How to Convert String to Array of Objects JavaScript ? Given a string, the task is to convert the given string to an array of objects using JavaScript. It is a common task, especially when working with JSON data received from a server or API. Below are the methods that allow us to convert string to an array of objects:Table of ContentUsing JSON.parse()
4 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 store a key=> value array in JavaScript ? In JavaScript, storing a key-value array means creating an object where each key is associated with a specific value. This allows you to store and retrieve data using named keys instead of numeric indices, enabling more intuitive access to the stored information.Here are some common approaches:Table
4 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
JavaScript - Print Object by id in an Array of Objects Here are the various methods to print objects by id in an array of objects in JavaScript1. Using Array.filter() MethodThe Array.filter() method, creates a new array containing only the object with the specified ID. JavaScriptconst a = [ { id: 1, name: "Alia" }, { id: 2, name: "Dua" }, { id: 3, name:
3 min read