How to use reduce Method In Javascript
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.
// 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) => {
let temp = acc.find((o) => {
JSON.stringify(o) === JSON.stringify(obj);
});
if (!temp) {
acc.push(obj);
}
return acc;
}, []);
// Output
console.log(output);
Output
[ { articleId: 101, title: 'Introduction to JavaScript' }, { articleId: 102, title: 'Arrays in JavaScript' }, { articleId: 101, title: 'Introduction to JavaScript' }, { articleId: 103, title: ...
How to Return an Array of Unique Objects in JavaScript ?
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:
Table of Content
- Using Set
- Using filter Method
- Using reduce Method
- Using map Method
- Using Object Key for Tracking Unique Objects