How to usethe reduce() method in Javascript
The reduce() method in JavaScript applies a function to each element of an array, accumulating a single result, and returns the final output.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr),
initialValue );
Example: In this example, we are using the reduce() method and create an array of arrays containing fruits of the same color. The resultArray logs the grouped fruits.
const fruits = [
{
fruit_name: "Apple",
fruit_color: "Red",
},
{
fruit_name: "Pomegranate",
fruit_color: "Red",
},
{
fruit_name: "Grapes",
fruit_color: "Green",
},
{
fruit_name: "Kiwi",
fruit_color: "Green",
},
];
const groupedByColor = fruits.reduce((acc, fruit) => {
const color = fruit.fruit_color;
(acc[color] = acc[color] || []).push(fruit);
return acc;
}, {});
const resultArray = Object.values(groupedByColor);
console.log(resultArray);
Output
[ [ { fruit_name: 'Apple', fruit_color: 'Red' }, { fruit_name: 'Pomegranate', fruit_color: 'Red' } ], [ { fruit_name: 'Grapes', fruit_color: 'Green' }, { fruit_name: 'Kiwi', frui...
Output
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', fruit_color: 'Green' }
]
]
How to group objects in an array based on a common property into an array of arrays in JavaScript ?
In this article, we will try to understand how we may easily group objects in an array based on a common property into an array of arrays in JavaScript with the help of an example itself. Grouping objects in an array based on a common property into an array of arrays in JavaScript. Organize data by shared property for efficient data manipulation.
Several methods can be used to group objects in an array based on a common property:
Table of Content
- Approach 1: Using Array.filter() method
- Approach 2: Using Object.values()
- Approach 3: Using the reduce() method
- Approach 4: Using for…of loop
- Approach 5: Using forEach()
- Approach 6: Using Map