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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read