How to use the forEach() method with an object as a map In Javascript
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.
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' } ] }
Grouping Nested Array in JavaScript
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:
Table of Content
- Using the reduce() method
- Using the forEach() method with an object as a map