Categorize

2 snippets across 2 stacks - JavaScript, Python

JSJavaScript

Object.groupBy()

JS · Modern Features
Syntax
Object.groupBy(iterable, keyFn)
Example
const people = [
  { name: "Ava", department: "Engineering" },
  { name: "Bo", department: "Design" },
  { name: "Cara", department: "Engineering" },
  { name: "Dan", department: "Design" },
  { name: "Eve", department: "Marketing" },
];

const byDept = Object.groupBy(people, p => p.department);
console.log(byDept.Engineering);
// [{ name: "Ava", ... }, { name: "Cara", ... }]
console.log(Object.keys(byDept));
// ["Engineering", "Design", "Marketing"]

Note ES2024. Returns a null-prototype object. For Map output, use Map.groupBy() instead. Replaces the common reduce-based grouping pattern.

PYPython

itertools.groupby

PY · Comprehensions & Generators
Syntax
from itertools import groupby
for key, group in groupby(iterable, key=func):
Example
from itertools import groupby

transactions = [
    {"type": "credit", "amount": 100},
    {"type": "credit", "amount": 200},
    {"type": "debit", "amount": 50},
    {"type": "debit", "amount": 75},
]

# Must be sorted by the grouping key first!
for ttype, group in groupby(transactions, key=lambda t: t["type"]):
    amounts = [t["amount"] for t in group]
    print(f"{ttype}: {amounts}")
Output
credit: [100, 200]
debit: [50, 75]

Note groupby only groups consecutive items with the same key. Sort the data by the key first, or you get fragmented groups.

Frequently asked questions

How does JavaScript handle categorize?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Object.groupBy()" snippet in JavaScript uses `Object.groupBy(iterable, keyFn)`.
Which code does the JavaScript example use?
The "Object.groupBy()" snippet uses `Object.groupBy(iterable, keyFn)`, from the Modern Features section of the JavaScript cheat sheet.
Which stacks cover "categorize" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Object.groupBy()": ES2024. Returns a null-prototype object. For Map output, use Map.groupBy() instead. Replaces the common reduce-based grouping pattern.