Rules Hub

Coding Rules Library

← Back to all rules
fullstack ruleStack: typescript
clean-codejavascriptes2024readabilityrefactoring

Prefer Object.groupBy for data grouping

Use the standardized Object.groupBy method instead of manual iteration to group array items.

PR: Feat/FCK-2384 - Upgrade MyFa Watchlist functionality #4232Created: Dec 7, 2025

Bad example

Old codets
1const inventory = [
2 { name: 'asparagus', type: 'vegetables' },
3 { name: 'banana', type: 'fruit' },
4 { name: 'goat', type: 'meat' },
5];
6
7// Bad: Manual imperative iteration to group items
8const grouped: Record<string, typeof inventory> = {};
9
10inventory.forEach((item) => {
11 const key = item.type;
12 if (!grouped[key]) {
13 grouped[key] = [];
14 }
15 grouped[key].push(item);
16});

Explanation (EN)

Manually initializing an object, checking for key existence, and pushing to an array is imperative boilerplate. It creates noise and increases the chance of minor bugs.

Objašnjenje (HR)

Ručno inicijaliziranje objekta, provjera postojanja ključa i dodavanje u niz je imperativan boilerplate kod. To stvara šum i povećava šansu za sitne greške.

Good example

New codets
1const inventory = [
2 { name: 'asparagus', type: 'vegetables' },
3 { name: 'banana', type: 'fruit' },
4 { name: 'goat', type: 'meat' },
5];
6
7// Good: Declarative standardized method
8const grouped = Object.groupBy(inventory, ({ type }) => type);

Explanation (EN)

Object.groupBy (introduced in ES2024) allows for a declarative, one-line solution to group elements. It clearly communicates intent and is now part of the standard library.

Objašnjenje (HR)

Object.groupBy (uveden u ES2024) omogućuje deklarativno rješenje u jednoj liniji za grupiranje elemenata. Jasno komunicira namjeru i sada je dio standardne biblioteke.

Notes (EN)

Requires 'ES2024' or newer in your tsconfig 'lib' setting. Use Map.groupBy if you need keys that are not strings.

Bilješke (HR)

Zahtijeva 'ES2024' ili noviji u 'lib' postavci unutar tsconfig-a. Koristite Map.groupBy ako trebate ključeve koji nisu stringovi.