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 view array of a structure in JavaScript ?
The Javascript arrays are heterogeneous. The structure of the array is the same which is enclosed between two square brackets [ ], and the string should be enclosed between either "double quotes" or 'single quotes'. You can get the structure of by using JSON.stringify() or not, here you will see the
2 min read
How to Convert an Array of Objects to Map in JavaScript?
Here are the different methods to convert an array of objects into a Map in JavaScript 1. Using new Map() ConstructorThe Map constructor can directly create a Map from an array of key-value pairs. If each object in the array has a specific key-value structure, you can map it accordingly. [GFGTABS] J
4 min read
How to use forEach with an Array of Objects in JavaScript ?
Using the forEach() method with an array of objects in JavaScript is essential for iterating over collections and performing operations on each object. This guide explores effective techniques to utilize forEach() for array manipulation, enhancing your coding skills. Syntax: array.forEach( function(
3 min read
How to Move a Key in an Array of Objects using JavaScript?
The JavaScript array of objects is a type of array that contains JavaScript objects as its elements. You can move or add a key to these types of arrays using the below methods in JavaScript: Table of Content Using Object Destructuring and Map()Using forEach() methodUsing for...of LoopUsing reduce()
5 min read
How to Convert String of Objects to Array in JavaScript ?
This article will show you how to convert a string of objects to an array in JavaScript. You have a string representing objects, and you need to convert it into an actual array of objects for further processing. This is a common scenario when dealing with JSON data received from a server or stored i
4 min read
How to Push an Array into Object in JavaScript?
To push an array into the Object in JavaScript, we will be using the JavaScript Array push() method. First, ensure that the object contains a property to hold the array data. Then use the push function to add the new array in the object. Understanding the push() MethodThe array push() method adds on
2 min read
How to Store an Object Inside an Array in JavaScript ?
Storing an object inside an array in JavScript involves placing the object as an element within the array. The array becomes a collection of objects, allowing for convenient organization and manipulation of multiple data structures in a single container. Following are the approaches through which it
3 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 JavaScript 1. 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 (l
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
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