var newly = [
                {"id":"15","cm_id":"31","name":"nims","total":1},
                {"id":"15","cm_id":"61","name":"bims forum",,"total":3},
                {"id":"80","cm_id":"198","name":"rims for topic",,"total":2}
                ];

Saya ingin memfilter filter array di atas berdasarkan id dan menemukan jumlah nilai total Contoh: id-> 15 total -> 4

Mohon saran bagaimana menggunakan filter dan pengurangan bersama untuk mengurutkan array berdasarkan id dan menghitung total untuk setiap id.

0
candish dd 8 Mei 2021, 22:20

2 jawaban

Jawaban Terbaik

Gunakan objek yang Anda atur nilai id sebagai kunci dan jumlah total sebagai nilai

var newly = [
                {"id":"15","cm_id":"31","name":"nims","total":1},
                {"id":"15","cm_id":"61","name":"bims forum","total":3},
                {"id":"80","cm_id":"198","name":"rims for topic","total":2}
                ];
                
 var idTotals = {};
 
 newly.forEach(({id, total}) => idTotals[id] = (idTotals[id] || 0) + total)
 
 console.log(idTotals)
0
charlietfl 8 Mei 2021, 19:51

Anda dapat mencoba metode ini

var totalCount = {};
var newly = [
                {"id":"15","cm_id":"31","name":"nims","total":1},
                {"id":"15","cm_id":"61","name":"bims forum","total":3},
                {"id":"80","cm_id":"198","name":"rims for topic","total":2}
            ];

for(const {id,total} of newly) {
    totalCount[id] = (id in totalCount) ? totalCount[id]+=total : total
}  

for(const id in totalCount){
    console.log(`id-> ${id} total -> ${totalCount[id]}`)
}
0
HSN HK 8 Mei 2021, 20:24