How to use Array.prototype.reduce In Javascript
The reduce method is used to separate an array of objects into multiple objects based on a specified property. This method initializes an empty object as an accumulator and iterates through the array, grouping objects by the specified property. It checks whether a property value exists in the accumulator, creating a new array for that value if it doesn’t, and then appends the current object to that array.
Example: In this, the reduce function iterates over the array and groups fruits based on the category.
// Array of objects
const array = [
{ id: 1, category: "A", value: "apple" },
{ id: 2, category: "B", value: "banana" },
{ id: 3, category: "A", value: "avocado" },
];
const groupedObjects = array.reduce((result, obj) => {
(result[obj.category] = result[obj.category] || []).push(obj);
return result;
}, {});
// Output
console.log(groupedObjects);
Output
{ A: [ { id: 1, category: 'A', value: 'apple' }, { id: 3, category: 'A', value: 'avocado' } ], B: [ { id: 2, category: 'B', value: 'banana' } ] }
How to Separate Array of Objects into Multiple Objects in JavaScript ?
In JavaScript, the task of separating an array of objects into multiple objects involves organizing and restructuring data based on specific criteria or properties. This process is often necessary when dealing with datasets that need to be grouped or segmented for easier analysis or manipulation.
There are various methods to achieve this separation which are as follows
Table of Content
- Using Array.prototype.reduce
- Using Array.prototype.forEach
- Using Map data structure
- Using Lodash _.groupBy