How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Last Updated :
17 Jul, 2024
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 various methods to convert an array of objects into a unique array of objects which are as follows:
Using Set
This approach uses the Set data structure in JavaScript, which automatically removes duplicate values. By mapping the array of objects to their JSON representations, the Set eliminates duplicate string representations, and then the unique objects are reconstructed.
Syntax:
let mySet = new Set();
Example: Using Set to create a unique array of objects by stringifying and parsing their JSON representations, eliminating duplicates based on content.
JavaScript
let arr = [
{ id: 1, name: "Geek1" },
{ id: 2, name: "Geek2" },
{ id: 1, name: "Geek1" },
{ id: 3, name: "Geek3" },
];
// unique objects using Set
let uniqueArr =
[...new Set(arr.map(JSON.stringify))].map(JSON.parse);
// printing output
console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);
OutputInput Array: [
{ id: 1, name: 'Geek1' },
{ id: 2, name: 'Geek2' },
{ id: 1, name: 'Geek1' },
{ id: 3, name: 'Geek3' }
]
Unique Array: [
{ id: 1, name: 'Geek1' },
{ id: 2, name: 'Geek2' },
...
Using filter() and indexOf() methods
The approach uses filter() and indexOf() to create a unique array by checking the index of each object's first occurrence based on JSON string representation for precise comparison. This ensures the removal of duplicate objects from the original array.
Syntax:
let arr = inputArray.filter((value, index, self) => {
return self.indexOf(value) === index;
});
Example: Filtering out duplicate objects from the input array using filter() and indexOf() based on JSON string comparison, resulting in a unique array.
JavaScript
let arr = [
{ id: 1, name: "Geek1" },
{ id: 2, name: "Geek2" },
{ id: 1, name: "Geek1" },
{ id: 3, name: "Geek3" },
];
// Unique array using filter and indexOf functions
let uniqueArr = arr.filter(
(value, index, self) =>
self.findIndex((obj) =>
JSON.stringify(obj) === JSON.stringify(value)) ===
index
);
// Printing output
console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);
OutputInput Array: [
{ id: 1, name: 'Geek1' },
{ id: 2, name: 'Geek2' },
{ id: 1, name: 'Geek1' },
{ id: 3, name: 'Geek3' }
]
Unique Array: [
{ id: 1, name: 'Geek1' },
{ id: 2, name: 'Geek2' },
...
Using Map
This approach uses a Map to efficiently remove duplicate objects from an array. It iterates through the input array, converts each object to a string using JSON.stringify as the key, and checks if the Map already has that key. If not, it adds the key to the Map and pushes the corresponding object to the unique array. This method ensures that unique objects are retained in the final array.
Syntax:
let newArray = originalArray.map((currentValue, index, array) => {
// code
});
Example: Removing duplicate objects from the input array using a Map to track unique object keys based on their JSON string representation, resulting in a unique array.
JavaScript
let arr = [
{ id: 1, name: "Geek1" },
{ id: 2, name: "Geek2" },
{ id: 1, name: "Geek1" },
{ id: 3, name: "Geek3" },
];
let map = new Map();
// Removing duplicate objects using map
let uniqueArr = [];
arr.forEach((obj) => {
const key = JSON.stringify(obj);
if (!map.has(key)) {
map.set(key, true);
uniqueArr.push(obj);
}
});
// Printing output
console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);
OutputInput Array: [
{ id: 1, name: 'Geek1' },
{ id: 2, name: 'Geek2' },
{ id: 1, name: 'Geek1' },
{ id: 3, name: 'Geek3' }
]
Unique Array: [
{ id: 1, name: 'Geek1' },
{ id: 2, name: 'Geek2' },
...
Using reduce()
The below approach uses the reduce() method to create a unique array of objects by comparing each object's string representation. The accumulator (acc) is updated only if the current object is not already present in the accumulator, effectively removing duplicates based on their stringified form.
Syntax:
let result = array.reduce((accumulator, currentValue, index, array) => {
//code
}, initialValue);
Example: Using the reduce method, this approach iterates through the input array, checking for duplicate objects based on their stringified representations.
JavaScript
let arr = [
{ id: 1, name: "Geek1" },
{ id: 2, name: "Geek2" },
{ id: 1, name: "Geek1" },
{ id: 3, name: "Geek3" },
];
// Removing objects using reduce()
let uniqueArr = arr.reduce((acc, obj) => {
const existingObj = acc.find(
(item) => JSON.stringify(item)
=== JSON.stringify(obj)
);
if (!existingObj) {
acc.push(obj);
}
return acc;
}, []);
// Printing output
console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);
OutputInput Array: [
{ id: 1, name: 'Geek1' },
{ id: 2, name: 'Geek2' },
{ id: 1, name: 'Geek1' },
{ id: 3, name: 'Geek3' }
]
Unique Array: [
{ id: 1, name: 'Geek1' },
{ id: 2, name: 'Geek2' },
...
Using Lodash Library
Using the Lodash library's uniqWith function with a custom comparison function compares objects for uniqueness. It returns an array of unique objects by comparing their properties or values, allowing for flexible and efficient handling of object uniqueness.
Example: In this example we use Lodash's _.uniqWith and _.isEqual to remove duplicate objects from the array.
JavaScript
const _ = require('lodash');
let arr = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, name: 'Alice' }
];
let uniqueObjects = _.uniqWith(arr, _.isEqual);
console.log(uniqueObjects);
Output
[
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]
Using some() Method
This approach uses the some() method to create a unique array of objects. The some() method checks if at least one element in the array passes the test implemented by the provided function. If an object with the same key already exists in the unique array, it is not added again.
Syntax:
array.some(callback(element[, index[, array]])[, thisArg])
Example: The below example uses the some() method to remove duplicate objects from an array based on a specific key in JavaScript.
JavaScript
let arr = [
{ id: 1, name: "Geek1" },
{ id: 2, name: "Geek2" },
{ id: 1, name: "Geek1" },
{ id: 3, name: "Geek3" },
];
// Using some() to ensure unique objects
let uniqueArr = [];
arr.forEach(obj => {
if (!uniqueArr.some(item => item.id === obj.id && item.name === obj.name)) {
uniqueArr.push(obj);
}
});
console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);
OutputInput Array: [
{ id: 1, name: 'Geek1' },
{ id: 2, name: 'Geek2' },
{ id: 1, name: 'Geek1' },
{ id: 3, name: 'Geek3' }
]
Unique Array: [
{ id: 1, name: 'Geek1' },
{ id: 2, name: 'Geek2' },
...
Using ES6 Find Method
This approach uses the ES6 find method to create a unique array of objects. The find method returns the first element in the array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
Syntax:
array.find(callback(element[, index[, array]])[, thisArg])
Example: The following example uses the find method to remove duplicate objects from an array by checking if an object with the same properties already exists in the unique array.
JavaScript
let arr = [
{ id: 1, name: "Geek1" },
{ id: 2, name: "Geek2" },
{ id: 1, name: "Geek1" },
{ id: 3, name: "Geek3" },
];
// Using find() to ensure unique objects
let uniqueArr = [];
arr.forEach(obj => {
if (!uniqueArr.find(item => item.id === obj.id && item.name === obj.name)) {
uniqueArr.push(obj);
}
});
console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);
OutputInput Array: [
{ id: 1, name: 'Geek1' },
{ id: 2, name: 'Geek2' },
{ id: 1, name: 'Geek1' },
{ id: 3, name: 'Geek3' }
]
Unique Array: [
{ id: 1, name: 'Geek1' },
{ id: 2, name: 'Geek2' },
...
Using reduce() with Set
This approach uses the reduce method along with a Set to track seen object IDs. It ensures that only unique objects (based on a specified key) are added to the result array.
Example: Using reduce and Set to remove duplicate objects based on a specific key (e.g., id).
JavaScript
let arr = [
{ id: 1, name: "Geek1" },
{ id: 2, name: "Geek2" },
{ id: 1, name: "Geek1" },
{ id: 3, name: "Geek3" },
];
// Using reduce and Set to ensure unique objects based on id
let uniqueArr = arr.reduce((acc, obj) => {
if (!acc.set) acc.set = new Set();
// Check if the id has already been seen
if (!acc.set.has(obj.id)) {
acc.set.add(obj.id);
acc.result.push(obj);
}
return acc;
}, { set: null, result: [] }).result;
console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);
OutputInput Array: [
{ id: 1, name: 'Geek1' },
{ id: 2, name: 'Geek2' },
{ id: 1, name: 'Geek1' },
{ id: 3, name: 'Geek3' }
]
Unique Array: [
{ id: 1, name: 'Geek1' },
{ id: 2, name: 'Geek2' },
...
Similar Reads
How to Convert an Object into Array of Objects in JavaScript?
Here are the different methods to convert an object into an array of objects in JavaScript1. Using Object.values() methodObject.values() method extracts the property values of an object and returns them as an array, converting the original object into an array of objects.JavaScriptconst a = { java:
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
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 Convert an Array of Objects to Map in JavaScript?
Here are the different methods to convert an array of objects into a Map in JavaScript1. 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.JavaScriptcon
3 min read
How to convert Object's array to an array using JavaScript ?
Given an array of objects and the task is to convert the object values to an array with the help of JavaScript. There are two approaches that are discussed below: Approach 1:We can use the map() method and return the values of each object which makes the array. Example: html<!DOCTYPE HTML>
2 min read
How to Convert an Array of Objects into Object in TypeScript ?
Converting an array of objects into a single object is a common task in JavaScript and TypeScript programming, especially when you want to restructure data for easier access. In this article, we will see how to convert an array of objects into objects in TypeScript.We are given an array of objects a
3 min read
How to Convert Object to Array in JavaScript?
In this article, we will learn how to convert an Object to an Array in JavaScript. Given an object, the task is to convert an object to an Array in JavaScript. Objects and Arrays are two fundamental data structures. Sometimes, it's necessary to convert an object to an array for various reasons, such
4 min read
How to Create Array of Objects From Keys & Values of Another Object in JavaScript ?
Creating an array of objects from the keys and values of another object involves transforming the key-value pairs of the original object into individual objects within an array. Each object in the array represents a key-value pair from the source object. Below approaches can be used to accomplish th
3 min read
How to convert arguments object into an array in JavaScript ?
The arguments object is an array-like object that represents the arguments passed in when invoking a function. This array-like object does not have the array prototype chain, hence it cannot use any of the array methods. This object can be converted into a proper array using two approaches: Method 1
5 min read
How to remove object from array of objects using JavaScript ?
Removing an object from an array of objects in JavaScript refers to the process of eliminating a specific object from the array based on certain conditions, like matching a property value. This task is common in data manipulation, ensuring the array only contains the desired elements.There are two a
2 min read