Group by key

2 snippets across 2 stacks — JavaScript, Python

JSJavaScript

Map.groupBy()

JS · Modern Features
syntax
Map.groupBy(iterable, keyFn)
example
const items = [
  { name: "Apple", price: 1.2 },
  { name: "Steak", price: 15 },
  { name: "Bread", price: 2.5 },
  { name: "Salmon", price: 12 },
];

const byRange = Map.groupBy(items, item =>
  item.price > 10 ? "expensive" : "affordable"
);
console.log(byRange.get("expensive"));
// [{ name: "Steak"... }, { name: "Salmon"... }]

Note ES2024. Similar to Object.groupBy but returns a Map, which supports any key type (objects, symbols, etc.).

PYPython

defaultdict

PY · Dictionaries
syntax
from collections import defaultdict
dd = defaultdict(factory)
example
from collections import defaultdict

word_count = defaultdict(int)
for word in "the cat sat on the mat".split():
    word_count[word] += 1
print(dict(word_count))
output
{'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}

Note defaultdict auto-creates missing keys using the factory function. Common factories: int (0), list ([]), set (set()).