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()).

Frequently asked questions

How does JavaScript handle group by key?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Map.groupBy()" snippet in JavaScript uses `Map.groupBy(iterable, keyFn)`.
Which code does the JavaScript example use?
The "Map.groupBy()" snippet uses `Map.groupBy(iterable, keyFn)`, from the Modern Features section of the JavaScript cheat sheet.
Which stacks cover "group by key" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Map.groupBy()": ES2024. Similar to Object.groupBy but returns a Map, which supports any key type (objects, symbols, etc.).