Last active
March 1, 2021 06:41
-
-
Save debbysa/800ccb1c9da6c90564a3e35941d4fe91 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
// 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