Reputation: 1726
I have this array of objects which i need to group by the name property, and i need a new array that sums up all the objects with the same name.
0:{id: 2, percent: "0.5968877829730651%", barGraphClass: "background-orange", labelClass: "background-orange", name: "cadastro pendente", …}
1:{id: 4, percent: "0.8286446806061278%", barGraphClass: "background-orange", labelClass: "background-orange", name: "cadastro pendente", …}
2:{id: 1, percent: "95.64138595007097%", barGraphClass: "background-toal", labelClass: "background-toal", name: "GTINs em uso", …}
3:{id: 3, percent: "2.1742168007401386%", barGraphClass: "background-orange", labelClass: "background-orange", name: "cadastro pendente", …}
4:{id: 5, percent: "0.1384810669784176%", barGraphClass: "background-orange", labelClass: "background-orange", name: "cadastro pendente", …}
5:{id: 6, percent: "0.2222506510683319%", barGraphClass: "background-orange", labelClass: "background-orange", name: "cadastro pendente", …}
6:{id: 7, percent: "0.39811621251585005%", barGraphClass: "background-orange", labelClass: "background-orange", name: "cadastro pendente", …}
7:{id: 8, percent: "0.000016855047100586368%", barGraphClass: "background-peach", labelClass: "background-peach", name: "GTINs bloqueados", …}
What i have tried is this const grouped = _.groupBy(newArray, 'name');
.
It does group by the name, but it doesnt sum up the values, only creates 3 separeate arrays and keeps the equal values
Upvotes: 1
Views: 58
Reputation: 222722
You can use .map and .Sumby
var data = [
{
"id": 2,
"percent": 0.5968877829730651,
"barGraphClass": "background-orange",
"labelClass": "background-orange",
"name": "cadastro pendente"
},
{
"id": 4,
"percent": 0.8286446806061278,
"barGraphClass": "background-orange",
"labelClass": "background-orange",
"name": "cadastro pendente"
},
{
"id": 1,
"percent": 95.64138595007097,
"barGraphClass": "background-toal",
"labelClass": "background-toal",
"name": "GTINs em uso"
}
]
const ans = _(data)
.groupBy('name')
.map((name, id) => ({
name: id,
payout: _.sumBy(name, 'percent')
}))
.value()
console.log(ans);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
Upvotes: 2