Back to Objects & JSONMedium
Exercise 5: Count by Key
Problem Statement
Given array of users `{role}`, function `countByRole(users)` banao.
Output: `{ admin: 2, user: 5 }`
Sample Output:
countByRole([{role:"admin"},{role:"user"},{role:"admin"}]) => {admin: 2, user: 1}
countByRole([{role:"user"}]) => {user: 1}Solution
const countByRole = (users) =>
users.reduce((acc, u) => {
acc[u.role] = (acc[u.role] ?? 0) + 1;
return acc;
}, {});Explanation
Overall Goal:
- Users array se role-wise count banana.
- Output:
{admin: 2, user: 5}format.
Solution:
const countByRole = (users) => users.reduce((acc, u) => { acc[u.role] = (acc[u.role] ?? 0) + 1; return acc; }, {});
Part 1: Reduce setup
users.reduce((acc, u) => {...}, {})reduce→ array ko traverse karke single object banana.{}→ initial value (empty object).acc→ accumulator (final object build ho raha hai).u→ current user from array.
Part 2: Count logic
acc[u.role] = (acc[u.role] ?? 0) + 1;u.role→ current user ki role (e.g., "admin", "user").acc[u.role] ?? 0→ nullish coalescing:- Agar role pehli baar aayi →
undefined→0use karo. - Agar role pehle se hai → existing count use karo.
+ 1→ count increment karo.acc[u.role] = ...→ updated count store karo.
Part 3: Return accumulator
return acc;→ updated accumulator return (next iteration ke liye).
Example:
- Input:
[{role: "admin"}, {role: "user"}, {role: "admin"}] - Step 1:
{admin: 1} - Step 2:
{admin: 1, user: 1} - Step 3:
{admin: 2, user: 1}
Real world:
- Dashboards: user statistics display.
- Analytics: category-wise counts.
- Reports: group by operations.