Created
April 8, 2021 08:01
-
-
Save r17x/0efb554b9ff9054d158b011ea43663d6 to your computer and use it in GitHub Desktop.
I dunno what i'm doing but i know it's just help people
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
// ISSUE https://www.facebook.com/permalink.php?story_fbid=2923264041231670&id=100006443087773 | |
// we have some data with item is | |
// { id: number, name: string, jumlahDonasi: number } | |
const data = [ | |
{ | |
id: 1, | |
name: "c", | |
jumlahDonasi: 2000, | |
}, | |
{ | |
id: 1, | |
name: "c", | |
jumlahDonasi: 5000, | |
}, | |
{ | |
id: 2, | |
name: "d", | |
jumlahDonasi: 2000, | |
}, | |
] | |
// we want to transform item of data, to be like this | |
// { id: number, name: string, jumlahDonasi: array(number) } | |
// #1 | |
let reduceDonation1 = (acc, cur, idx, src) => { | |
let maybeExist = acc.findIndex(item => item.id === cur.id); // will return 0,1,N by length of array and -1 when nothing | |
if(maybeExist >= 0){ | |
// we assume cur.id exist in `acc` & so we can push to acc[index].julahDonasi | |
// possibly error push when `jumlahDonasi` is not an array so you can make it more safely | |
acc[maybeExist].jumlahDonasi.push(cur.jumlahDonasi) | |
return acc | |
} | |
acc.push({...cur, jumlahDonasi: [cur.jumlahDonasi]}) | |
return acc | |
} | |
data.reduce(reduceDonation, []) // correctly when initiator is empty array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment