我想按CPF加总销售额,我设法将CPF分开,但我现在不知道如何做总和,请参阅下面的代码
var vendas = [{cpf: "14382435021", amount: 34.5 }, { cpf: "79785337006", amount: 12 }, { cpf: "79785337006", amount: 23.16 }, { cpf: "14382435021", amount: 46.4 }, { cpf: "88835414059", amount: 26.2 }, { cpf: "88835414059", amount: 199.9 }, { cpf: "79785337006", amount: 18.16 } ]
var resultados = {};
for(var i = 0; i < vendas.length; i++){
if(vendas[i].cpf){
if(!resultados[vendas[i].cpf]){
resultados[vendas[i].cpf] = []
}
resultados[vendas[i].cpf].push(vendas[i]);
}
}
console.log(resultados)
<script>
var vendas = [{cpf: "14382435021", amount: 34.5 }, { cpf: "79785337006", amount: 12 }, { cpf: "79785337006", amount: 23.16 }, { cpf: "14382435021", amount: 46.4 }, { cpf: "88835414059", amount: 26.2 }, { cpf: "88835414059", amount: 199.9 }, { cpf: "79785337006", amount: 18.16 } ]
var result = [];
vendas.reduce(function(res, value) {
if (!res[value.cpf]) {
res[value.cpf] = { cpf: value.cpf, amount: 0 };
result.push(res[value.cpf])
}
res[value.cpf].amount += value.amount;
return res;
}, {});
console.log(result)
</script>