Open In App

How to group objects in an array based on a common property into an array of arrays in JavaScript ?

Last Updated : 28 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Approach 1: Using Array.filter() method

In this approach, we will create an array having multiple objects in itself and then use Array.filter() method we will filter out certain values from that complete array of objects.

Syntax:

array.filter(callback(element, index, arr), thisValue);

Example: in this example, we are using the above-explained approach.

Javascript




let 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",
    },
];
let filtered_fruits = fruits.filter((fruit) =>
    fruit.fruit_color === "Red");
console.log(filtered_fruits);


Output

[
  { fruit_name: 'Apple', fruit_color: 'Red' },
  { fruit_name: 'Pomegranate', fruit_color: 'Red' }
]

Approach 2: Using Object.values()

In this approach, we will use the same array containing multiple objects which we have created previously, and here we will create another function that will be responsible for containing our logic for the above-enlightened problem statement.

Then the first part of our logic will be using Object.values() method that will actually accumulate all the object values for us and just after that we will use Array.reduce() method which will reduce our array into objects and then using nullish coalescing operator (??) we will either add the property value inside the accumulator value (part of reduce method) or we will add an empty array instead of it ([ ]). 

The second part of our logic says that we have to push the current value inside the accumulator value itself that contains the previously added value in it and then at the end, we will return the accumulator value itself.

Syntax:

Object.values(obj)

Example: This example shows the implementation of the above-explained approach.

Javascript




let 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",
    },
];
 
let groupingViaCommonProperty = Object.values(
    fruits.reduce((acc, current) => {
        acc[current.fruit_color] = acc[current.fruit_color] ?? [];
        acc[current.fruit_color].push(current);
        return acc;
    }, {})
);
console.log(groupingViaCommonProperty);


Output

[
  [
    { fruit_name: 'Apple', fruit_color: 'Red' },
    { fruit_name: 'Pomegranate', fruit_color: 'Red' }
  ],
  [
    { fruit_name: 'Grapes', fruit_color: 'Green' },
    { fruit_name: 'Kiwi', frui...

Approach 3: Using the reduce() method

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.

Javascript




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' }
]
]

Approach 4: Using for…of loop

The for…of loop in JavaScript iterates over iterable objects like arrays, strings, maps, sets, etc. We can use it to group objects in an array based on a common property.

Syntax:

for ( variable of iterableObjectName) {
...
}

Example: In this example, we are using the above-explained approach.

Javascript




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 = {};
 
for (const fruit of fruits) {
    const color = fruit.fruit_color;
    if (!groupedByColor[color]) {
        groupedByColor[color] = [fruit];
    } else {
        groupedByColor[color].push(fruit);
    }
}
 
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' }
]
]

Approach 5: Using forEach()

Using the forEach() method in JavaScript, we can iterate over each element in an array and group objects based on a common property.

Syntax:

array.forEach(callback(element, index, arr), thisValue)

Example: In this example, the forEach() loop iterates over each fruit in the fruits array. It checks the fruit_color property, creates an empty array for color if it doesn’t exist in the groupedByColor object, and then pushes the fruit into the corresponding array based on its color.

Javascript




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.forEach((fruit) => {
    const color = fruit.fruit_color;
    groupedByColor[color] = groupedByColor[color] || [];
    groupedByColor[color].push(fruit);
});
 
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', fruit_color: 'Green' }
]
]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads