1function groupBy(list, keyGetter) {
2 const map = new Map();
3 list.forEach((item) => {
4 const key = keyGetter(item);
5 const collection = map.get(key);
6 if (!collection) {
7 map.set(key, [item]);
8 } else {
9 collection.push(item);
10 }
11 });
12 return map;
13}
14
15// example usage
16
17const pets = [
18 {type:"Dog", name:"Spot"},
19 {type:"Cat", name:"Tiger"},
20 {type:"Dog", name:"Rover"},
21 {type:"Cat", name:"Leo"}
22];
23
24const grouped = groupBy(pets, pet => pet.type);
25
26console.log(grouped.get("Dog")); // -> [{type:"Dog", name:"Spot"}, {type:"Dog", name:"Rover"}]
27console.log(grouped.get("Cat")); // -> [{type:"Cat", name:"Tiger"}, {type:"Cat", name:"Leo"}]
28
29