π Goal: Group Array Items by Property (e.g. city
)
In TypeScript, you can group items from an array by any field (like city
) using either an Object or a Map. Both work well β choose based on your needs.
π¦ Option 1: Using a Plain Object
β
When to Use:
- Simpler use case
- Keys are strings
- You donβt need
Map
features
π§± Example
ts
interface Person {
name: string;
age: number;
city: string;
}
const people: Person[] = [
{ name: 'Alice', age: 25, city: 'New York' },
{ name: 'Bob', age: 30, city: 'San Francisco' },
{ name: 'Charlie', age: 35, city: 'New York' },
{ name: 'David', age: 40, city: 'San Francisco' },
{ name: 'Eve', age: 45, city: 'Chicago' }
];
const groupByCity = (array: Person[]): Record<string, Person[]> => {
return array.reduce((acc, person) => {
(acc[person.city] = acc[person.city] || []).push(person);
return acc;
}, {} as Record<string, Person[]>);
};
console.log(groupByCity(people));
π§Ύ Output:
ts
{
"New York": [...],
"San Francisco": [...],
"Chicago": [...]
}
πΊοΈ Option 2: Using a Map<string, Person[]>
β
When to Use:
- Need non-string keys (e.g. enums, objects)
- Want more clarity and method support
- Avoid prototype key collisions
π§± Example
ts
const groupByCity = (array: Person[]): Map<string, Person[]> => {
return array.reduce((acc, person) => {
if (!acc.has(person.city)) {
acc.set(person.city, []);
}
acc.get(person.city)!.push(person);
return acc;
}, new Map<string, Person[]>());
};
const grouped = groupByCity(people);
grouped.forEach((group, city) => {
console.log(`City: ${city}`);
console.log(group);
});
π§Ύ Output:
css
City: New York
[ { name: 'Alice', ... }, { name: 'Charlie', ... } ]
City: San Francisco
[ { name: 'Bob', ... }, { name: 'David', ... } ]
City: Chicago
[ { name: 'Eve', ... } ]
π Recap Table
FeatureObjectMapKey TypeString onlyAny type (string, number, object...)Method SupportBasic JS operations.has()
, .get()
, .set()
Ordered IterationNot guaranteedPreserves insertion orderPrototype PollutionPossibleAvoided