Groupby

3 snippets across 2 stacks — Python, JavaScript

Also written as groupBy

PYPython

itertools Highlights

PY · Comprehensions & Generators
syntax
import itertools
example
from itertools import chain, islice, groupby, product

# Chain multiple iterables
all_items = list(chain([1, 2], [3, 4], [5]))
print(all_items)

# Take first N from any iterable
first_three = list(islice(range(1000000), 3))
print(first_three)

# Cartesian product
sizes = ["S", "M"]
colors = ["red", "blue"]
combos = list(product(sizes, colors))
print(combos)
output
[1, 2, 3, 4, 5]
[1, 2, 3]
[('S', 'red'), ('S', 'blue'), ('M', 'red'), ('M', 'blue')]

Note itertools functions return lazy iterators. They compose well and avoid creating intermediate lists. See also: accumulate, starmap, tee, zip_longest.

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.

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.