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 andar category field 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.
  • items parameter: ye array of products / objects hai.

Line 2: reduce start

  • items.reduce((acc, it) => { ... }, {});
  • reduce ka kaam: pure array ko traverse karke ek single result banana.
  • acc (accumulator) → yaha final object build ho raha hai.
  • it (item) → current element from items.
  • Last argument {} → initial value, yani start me acc = {} (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/undefined hai → 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 item it ko us category wale array me add kar rahe hain.
  • Ab acc kuch aisa dikh sakta hai:
  • { laptop: [/* laptops */], mobile: [/* mobiles */] }

Line 5: return acc

  • return acc;reduce ke har step ke baad updated accumulator wapas bhejna zaroori hai.
  • Next item ke liye ye hi acc starting point banega.

Final output:

  • Loop khatam hone par reduce complete 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).