1

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

  • Possible duplicate of [What is the most efficient method to groupby on a JavaScript array of objects?](https://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects) – masterfloda Mar 09 '18 at 18:21
  • Can you give us usable demo data ? – zfrisch Mar 09 '18 at 18:23
  • The array on the topic is the same im using, just need to group by the name "cadastro pendente" which is repeating itself, the groupBy separetes it into an array with 6 objects, i need 1 object with the values summed up – Daniel Bezerra De Menezes Mar 09 '18 at 18:26

1 Answers1

2

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>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396