This is my array of objects:
const cart = [
{ group: "group 1", qtd: 12, value: 65, term: 20 }, //index 0
{ group: "group 1", qtd: 10, value: 100, term: 20 }, //index 1
{ group: "group 1", qtd: 18, value: 40, term: 10 }, //index 2
{ group: "group 2", qtd: 5, value: 30, term: 25 }, //index 3
{ group: "group 2", qtd: 22, value: 10, term: 25 }, //index 4
{ group: "group 3", qtd: 6, value: 60, term: 12 } //index 5
];
And I need to do some treatments to get this output:
result = [
{ group: "group 1", value: 1780, term: 20 },
{ group: "group 1", value: 720, term: 10 },
{ group: "group 2", value: 370, term: 25 },
{ group: "group 3", value: 360, term: 12 }
];
If the group is equal and the term is equal too, I need to add the qtd and the value of the indexes that matches with this rule. In this exemple, index 0 and 1 matches with the rule, so I make (12 * 65) + (10 * 100) = 1780 | index 3 and 4 matches too, so I make (5 * 30) + (22 * 10) = 370. And if the terms doesn't match, I just sum like in the other cases and show separately, like in indexes 2 and 5.
First i was trying to get the distinct elements of this object and how much times and how many times did it repeat itself, so I use lodash for this:
const counts = _.countBy(cart, "group");
And the output:
{ 'group 1': 3, 'group 2': 2, 'group 3': 1 }
And from that logic I can't think of a solution
I already try I lot of logics but I can't get anywhere, I would be very grateful if someone could help me in this logic.