awelgorithms

Group values by a key

Updated

Grouping is key → list of items with that key. First time you see the key, put an empty list (or a one-item list). Later items append. The key is unique. The list grows.

What to focus on

Typical: anagram buckets (sorted letters → words), rows by id, remainder → numbers. The map's values are collections, not scalars.

Worked examples

by parity

a = [4, 1, 9, 2]
  1. even → [4,2]
  2. odd → [1,9]

Result: {0:[4,2], 1:[1,9]} if key is x%2

all one group

a = [2, 8, 4]
  1. all even

Result: {0:[2,8,4]}

empty

a = []
  1. no groups

Result: {}

Try it

Write groupBy(a, keyFn). a is an array of integers. keyFn is a function that takes one value and returns a key. Append each value onto the list for keyFn(value). Return the map of lists. a = [4, 1, 9, 2] → {0:[4,2], 1:[1,9]} if key is x%2. a = [2, 8, 4] → {0:[2,8,4]}. a = [] → {}.

a is a list of integers and may be empty. keyFn is a function from a value to a key. In this drill keyFn is x%2.

LeetCode problems that use this skill