Skip to content

Instantly share code, notes, and snippets.

@debbysa
Last active March 1, 2021 06:41
Show Gist options
  • Save debbysa/800ccb1c9da6c90564a3e35941d4fe91 to your computer and use it in GitHub Desktop.
Save debbysa/800ccb1c9da6c90564a3e35941d4fe91 to your computer and use it in GitHub Desktop.
// group object by property
const books = [
{
title: "Sebuah Seni Untuk Bersikap Bodo Amat",
author: "Mark Manson"
},
{
title: "Segala - galanya Ambyar",
author: "Mark Manson"
},
{
title: "Berani Bahagia",
author: " Ichiro Kishimi dan Fumitake Koga"
}
];
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, current) {
let key = current[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(current);
return acc;
}, {});
}
let groupBook = groupBy(books, 'author')
console.log(groupBook)
// hasilnya adalah :
// {
// Mark Manson: [
// { title: "Sebuah Seni Untuk Bersikap Bodo Amat", author: "Mark Manson"},
// { title: "Segala - galanya Ambyar", author: "Mark Manson"}
// ],
// Ichiro Kishimi dan Fumitake Koga: [
// { title: "Berani Bahagia", author: " Ichiro Kishimi dan Fumitake Koga"},
// ]
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment