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.