Exercise 2: Group By (category)
Problem Statement
Given products: `{id, category}`, function `groupByCategory(items)` banao jo category wise grouped object return kare.
Sample Output:
groupByCategory([{id:1,category:"laptop"},{id:2,category:"mobile"},{id:3,category:"laptop"}])
=> {laptop: [{id:1,category:"laptop"},{id:3,category:"laptop"}], mobile: [{id:2,category:"mobile"}]}Solution
const groupByCategory = (items) =>
items.reduce((acc, it) => {
(acc[it.category] ??= []).push(it);
return acc;
}, {});Explanation
Overall goal:
- Input:
items(array of objects) jisme har item ke andarcategoryfield hai. - Output: ek object
{ [category]: [items...] }jaha har key ek category hai.
Line 1: function header
const groupByCategory = (items) =>→ function ka naam clearly batata hai ki hum category ke basis par group karenge.itemsparameter: ye array of products / objects hai.
Line 2: reduce start
items.reduce((acc, it) => { ... }, {});reduceka kaam: pure array ko traverse karke ek single result banana.acc(accumulator) → yaha final object build ho raha hai.it(item) → current element fromitems.- Last argument
{}→ initial value, yani start meacc = {}(empty object).
Line 3: acc[it.category] ??= []
it.category→ current item ki category, jaise"laptop"ya"mobile".acc[it.category]→ us category ke liye abhi tak jo array bana hai.??=operator:- Agar
acc[it.category]null/undefinedhai → usko[](empty array) bana do. - Agar already array hai → usko as‑is chhod do.
- Is line ka matlab: “agar is category ke liye array nahi bana, to ab bana do.”
Line 4: .push(it)
.push(it)→ ab current itemitko us category wale array me add kar rahe hain.- Ab
acckuch aisa dikh sakta hai: { laptop: [/* laptops */], mobile: [/* mobiles */] }
Line 5: return acc
return acc;→reduceke har step ke baad updated accumulator wapas bhejna zaroori hai.- Next item ke liye ye hi
accstarting point banega.
Final output:
- Loop khatam hone par
reducecomplete object return karega, jo hum function se return kar dete hain.
Real world:
- Product listing pages (category wise cards).
- Blog posts ko topic ya author ke group me dikhana.
- Analytics me data ko group karna (status, role, type).