Skip to content

Instantly share code, notes, and snippets.

@ekrem-aktas
Created September 24, 2020 12:18
Show Gist options
  • Save ekrem-aktas/553945d603c62900b3b28bd5eb32d232 to your computer and use it in GitHub Desktop.
Save ekrem-aktas/553945d603c62900b3b28bd5eb32d232 to your computer and use it in GitHub Desktop.
function groupBy(arr, func){
return arr
.reduce((acc, item) => {
const key = func(item);
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(item);
return acc;
}, Object.create(null));
}
const basket = [
{ name:"apple", type: "fruit" },
{ name:"broccoli", type: "vegetable" },
{ name:"banana", type: "fruit" }
];
const grouped = groupBy(basket, food => food.type);
console.log(grouped);
/*
Outputs:
{
fruit: [
{name: "apple", type: "fruit"},
{name: "banana", type: "fruit"}
],
vegetable: [{ name:"broccoli", type: "vegetable" }]
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment