How to use reduce() In Javascript
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.
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);
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