Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Manipulate Object to group based on Array Object List in JavaScript
Grouping objects in JavaScript is a common operation when working with arrays of objects. This technique allows you to organize data by specific properties, making it easier to process and analyze related items together.
Understanding the Problem
Consider an array of objects representing people with properties like name, profession, and age. We want to group these objects by a specific property (like profession) to create an organized structure where each group contains all objects sharing that property value.
For example, grouping people by profession would create separate arrays for developers, teachers, engineers, etc. This organization makes it simple to perform operations on subsets of data that share common characteristics.
Using forEach() Method
The forEach() approach iterates through each object and builds the grouped structure step by step:
// Define array of objects
const persons = [
{ name: 'Alice', profession: 'Developer', age: 25 },
{ name: 'Bob', profession: 'Teacher', age: 30 },
{ name: 'Charlie', profession: 'Developer', age: 28 },
{ name: 'Diana', profession: 'Teacher', age: 35 },
{ name: 'Eve', profession: 'Engineer', age: 23 }
];
// Function to group objects by specified property
function groupObjects(array, property) {
const grouped = {};
array.forEach((obj) => {
const key = obj[property];
if (grouped[key]) {
grouped[key].push(obj);
} else {
grouped[key] = [obj];
}
});
return grouped;
}
const groupedByProfession = groupObjects(persons, "profession");
console.log(groupedByProfession);
{
Developer: [
{ name: 'Alice', profession: 'Developer', age: 25 },
{ name: 'Charlie', profession: 'Developer', age: 28 }
],
Teacher: [
{ name: 'Bob', profession: 'Teacher', age: 30 },
{ name: 'Diana', profession: 'Teacher', age: 35 }
],
Engineer: [
{ name: 'Eve', profession: 'Engineer', age: 23 }
]
}
Using reduce() Method
The reduce() method provides a more functional approach, accumulating results in a single pass:
// Sample array of objects
const items = [
{ name: 'apple', category: 'fruit', price: 1.2 },
{ name: 'banana', category: 'fruit', price: 0.8 },
{ name: 'carrot', category: 'vegetable', price: 0.5 },
{ name: 'orange', category: 'fruit', price: 1.5 },
{ name: 'spinach', category: 'vegetable', price: 2.0 }
];
// Group items by category using reduce
const groupedItems = items.reduce((accumulator, item) => {
const category = item.category;
if (!accumulator[category]) {
accumulator[category] = [];
}
accumulator[category].push(item);
return accumulator;
}, {});
console.log(groupedItems);
{
fruit: [
{ name: 'apple', category: 'fruit', price: 1.2 },
{ name: 'banana', category: 'fruit', price: 0.8 },
{ name: 'orange', category: 'fruit', price: 1.5 }
],
vegetable: [
{ name: 'carrot', category: 'vegetable', price: 0.5 },
{ name: 'spinach', category: 'vegetable', price: 2.0 }
]
}
Comparison of Methods
| Method | Approach | Readability | Best Use Case |
|---|---|---|---|
forEach() |
Imperative | More explicit | When you need side effects or complex logic |
reduce() |
Functional | More concise | When you want immutable, functional style |
Advanced Example: Multiple Grouping Criteria
const employees = [
{ name: 'John', department: 'IT', level: 'Senior' },
{ name: 'Jane', department: 'IT', level: 'Junior' },
{ name: 'Mike', department: 'HR', level: 'Senior' },
{ name: 'Sarah', department: 'HR', level: 'Junior' }
];
// Group by department, then by level
const nestedGroup = employees.reduce((acc, emp) => {
const dept = emp.department;
const level = emp.level;
if (!acc[dept]) {
acc[dept] = {};
}
if (!acc[dept][level]) {
acc[dept][level] = [];
}
acc[dept][level].push(emp);
return acc;
}, {});
console.log(JSON.stringify(nestedGroup, null, 2));
{
"IT": {
"Senior": [
{ "name": "John", "department": "IT", "level": "Senior" }
],
"Junior": [
{ "name": "Jane", "department": "IT", "level": "Junior" }
]
},
"HR": {
"Senior": [
{ "name": "Mike", "department": "HR", "level": "Senior" }
],
"Junior": [
{ "name": "Sarah", "department": "HR", "level": "Junior" }
]
}
}
Performance Considerations
Both methods have O(n) time complexity where n is the number of objects in the array. Each object is processed exactly once. Space complexity is also O(n) as the grouped result contains all original objects organized into different arrays.
Conclusion
Object grouping is essential for data organization in JavaScript. Use forEach() for explicit control and complex logic, or reduce() for functional, immutable approaches. Both methods efficiently organize array data by shared properties.
