- Adds current object into that city array.
- Real World Use Cases
- Group employees by department
- Group students by class
- Group products by category
- Group jobs by city
- Group candidates by skills
const users = [
{ name: "Raj", city: "Bangalore" },
{ name: "Amit", city: "Delhi" },
{ name: "John", city: "Bangalore" }
];
const grouped = users.reduce((acc, curr) => {
//console.log(curr);
if (!acc[curr.city]) {
acc[curr.city] = [];
}
acc[curr.city].push(curr);
return acc;
}, {});
console.log(grouped);
/*
output :
{
Bangalore: [
{ name: 'Raj', city: 'Bangalore' },
{ name: 'John', city: 'Bangalore' }
],
Delhi: [ { name: 'Amit', city: 'Delhi' } ]
}
*/
Understanding Step by Step
acc
acc means accumulator.
Initially:
{}
It stores the final grouped result.
curr
curr means current object.
First iteration:
{ name: "Raj", city: "Bangalore" }
PART 1
if (!acc[curr.city]) {
acc[curr.city] = [];
}
What is curr.city ?
For first object:
curr.city
Value:
"Bangalore"
So this becomes:
acc["Bangalore"]
First Iteration
Initially:
acc = {}
Check:
if (!acc["Bangalore"])
Since it does not exist:
undefined
Condition becomes TRUE.
Then:
acc["Bangalore"] = [];
Now accumulator becomes:
{
Bangalore: []
}
PART 2
acc[curr.city].push(curr);
This becomes:
acc["Bangalore"].push(curr)
Meaning:
[].push({ name: "Raj", city: "Bangalore" })
Now:
{
Bangalore: [
{ name: "Raj", city: "Bangalore" }
]
}
Second Iteration
Current object:
{ name: "Amit", city: "Delhi" }
Check:
if (!acc["Delhi"])
Delhi does not exist.
Create:
acc["Delhi"] = [];
Then push:
acc["Delhi"].push(curr)
Now:
{
Bangalore: [
{ name: "Raj", city: "Bangalore" }
],
Delhi: [
{ name: "Amit", city: "Delhi" }
]
}
Third Iteration
Current:
{ name: "John", city: "Bangalore" }
Check:
if (!acc["Bangalore"])
Now Bangalore already exists:
[
{ name: "Raj", city: "Bangalore" }
]
Condition becomes FALSE.
So it skips array creation.
Then:
acc["Bangalore"].push(curr)
Final Output:
{
Bangalore: [
{ name: "Raj", city: "Bangalore" },
{ name: "John", city: "Bangalore" }
],
Delhi: [
{ name: "Amit", city: "Delhi" }
]
}
Simple Meaning
This line:
acc[curr.city] = [];
Creates a new array if city does not exist.
This line:
acc[curr.city].push(curr);