Created
April 7, 2021 08:29
-
-
Save william-condori/62b29de8d21646cf0001bc1b351a6e97 to your computer and use it in GitHub Desktop.
Group By in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function groupBy(list, keyGetter) { | |
const map = new Map(); | |
list.forEach((item) => { | |
const key = keyGetter(item); | |
const collection = map.get(key); | |
if (!collection) { | |
map.set(key, [item]); | |
} else { | |
collection.push(item); | |
} | |
}); | |
return map; | |
} | |
// example usage | |
const pets = [ | |
{type:"Dog", name:"Spot"}, | |
{type:"Cat", name:"Tiger"}, | |
{type:"Dog", name:"Rover"}, | |
{type:"Cat", name:"Leo"} | |
]; | |
const grouped = groupBy(pets, pet => pet.type); | |
console.log(grouped.get("Dog")); // -> [{type:"Dog", name:"Spot"}, {type:"Dog", name:"Rover"}] | |
console.log(grouped.get("Cat")); // -> [{type:"Cat", name:"Tiger"}, {type:"Cat", name:"Leo"}] | |
const odd = Symbol(); | |
const even = Symbol(); | |
const numbers = [1,2,3,4,5,6,7]; | |
const oddEven = groupBy(numbers, x => (x % 2 === 1 ? odd : even)); | |
console.log(oddEven.get(odd)); // -> [1,3,5,7] | |
console.log(oddEven.get(even)); // -> [2,4,6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment