Programming & Development / April 18, 2025

Grouping Arrays in TypeScript Using Map or Object

TypeScript group by reduce group with map array grouping

πŸ”— 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


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex