Open In App

Grouping Nested Array in JavaScript

Last Updated : 02 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Grouping nested arrays in JavaScript involves arranging arrays within arrays based on a common key or property.

There are different approaches to group nested arrays in JavaScript which are as follows:

Using the reduce() method

This approach uses the reduce() method to group arrays within a nested array based on a shared key. It creates a new object where each key corresponds to a unique property value and the value is an array of objects with that property value.

Example: To demonstrate grouping a nested array in JavaScript using the reduce() method in JavaScript.

JavaScript
const students = [
  { name: 'Saurabh', div: 'A' },
  { name: 'Gaurav', div: 'C' },
  { name: 'Prasad', div: 'B' },
  { name: 'Rohit', div: 'C' },
  { name: 'Pratik', div: 'A' }
];

const groupedStudents = students
  .reduce((acc, curr) => {
    const key = curr.div;
    (acc[key] = acc[key] || [])
      .push(curr);
    return acc;
  }, {});

console.log(groupedStudents);

Output
{
  A: [ { name: 'Saurabh', div: 'A' }, { name: 'Pratik', div: 'A' } ],
  C: [ { name: 'Gaurav', div: 'C' }, { name: 'Rohit', div: 'C' } ],
  B: [ { name: 'Prasad', div: 'B' } ]
}

Using the forEach() method with an object as a map

In this approach we iterate over the nested array using the forEach() method and use an object as a map to group arrays based on a common key. For each element in the nested array, we check if the key already exists in the map object. If it does we push the element to the corresponding array. otherwise we create a new array for that key.

Example: To demonsrtate grouping nested array in JavaScript using the usesforEach() method with an object as a map to group nested arrays.

JavaScript
const students = [
  { name: 'Saurabh', div: 'A' },
  { name: 'Gaurav', div: 'C' },
  { name: 'Prasad', div: 'B' },
  { name: 'Rohit', div: 'C' },
  { name: 'Pratik', div: 'A' }
];

const groupedStudents = {};
students.forEach((student) => {
  const key = student.div;
  groupedStudents[key] = groupedStudents[key] || [];
  groupedStudents[key].push(student);
});

console.log(groupedStudents);

Output
{
  A: [ { name: 'Saurabh', div: 'A' }, { name: 'Pratik', div: 'A' } ],
  C: [ { name: 'Gaurav', div: 'C' }, { name: 'Rohit', div: 'C' } ],
  B: [ { name: 'Prasad', div: 'B' } ]
}


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads