How to use Map In Javascript
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.
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);
Output
Input 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' }, ...
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 various methods to convert an array of objects into a unique array of objects which are as follows:
Table of Content
- Using Set
- Using filter() and indexOf() methods
- Using Map
- Using reduce()
- Using Lodash Library
- Using some() Method