Created
September 24, 2020 12:18
-
-
Save ekrem-aktas/553945d603c62900b3b28bd5eb32d232 to your computer and use it in GitHub Desktop.
This file contains 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(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