1

i have an output like this:

[ { GolonganName: '3B - Niaga Besar', data: [ 172000 ] }, { GolonganName: '3A - Niaga Kecil', data: [ 76700 ] }, { GolonganName: '2B - Rumah Tangga Menengah', data: [ 57000 ] }, { GolonganName: 'IA - Rumah Tangga', data: [ 272000 ] }, { GolonganName: 'R5 - Instansi Pemerintah', data: [ 429300 ] }, { GolonganName: '3B - Niaga Besar', data: [ 0 ] }, { GolonganName: '3A - Niaga Kecil', data: [ 0 ] }, { GolonganName: '2B - Rumah Tangga Menengah', data: [ 50200 ] }, { GolonganName: 'IA - Rumah Tangga', data: [ 0 ] }, { GolonganName: 'R5 - Instansi Pemerintah', data: [ 1467000 ] } ] 

but i want to push my data with the same GolonganName into 1 data only like this:

[ { GolonganName: '3B - Niaga Besar', data: [ 172000, 0 ] }, { GolonganName: '3A - Niaga Kecil', data: [ 76700, 0 ] }, { GolonganName: '2B - Rumah Tangga Menengah', data: [ 57000, 50200 ] }, { GolonganName: 'IA - Rumah Tangga', data: [ 272000, 0 ] }, { GolonganName: 'R5 - Instansi Pemerintah', data: [ 429300, 1467000 ] }, ] 

i've tried using array.map but its not working properly

 let dataMap: any = seriesGolongan.map((item: any, i: any) => { const length = responseBillingTarget.length; let lenGol = responseGetGolongan.length; for (let index = 0; index < responseGetGolongan.length; index++) { const element = responseGetGolongan[index]; if (element.name == item.GolonganName) { if (length == 2) { resultGol.push({ GolonganName: item.GolonganName, data: [parseInt(item.data)], }); } } } }); 

how to solve it? can u guys help me pls ?

1 Answer 1

1

You can use grouping by hash approach:

const inputData = [{GolonganName:'3B - Niaga Besar',data:[172000]},{GolonganName:'3A - Niaga Kecil',data:[76700]},{GolonganName:'2B - Rumah Tangga Menengah',data:[57000]},{GolonganName:'IA - Rumah Tangga',data:[272000]},{GolonganName:'R5 - Instansi Pemerintah',data:[429300]},{GolonganName:'3B - Niaga Besar',data:[0]},{GolonganName:'3A - Niaga Kecil',data:[0]},{GolonganName:'2B - Rumah Tangga Menengah',data:[50200]},{GolonganName:'IA - Rumah Tangga',data:[0]},{GolonganName:'R5 - Instansi Pemerintah',data:[1467000]}]; const groups = inputData.reduce((acc, { GolonganName, data }) => { acc[GolonganName] ??= { GolonganName, data: [] }; acc[GolonganName].data.push(...data); return acc; }, {}); const result = Object.values(groups); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.