Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

group by, and sum, and generate a object for each array javascript

I need to group by id and sum, but I need a new object for each result:

let data = [
    {"id":"2018", "name":"test", "total":1200},
    {"id":"2019", "name":"wath", "total":1500},
    {"id":"2019", "name":"wath", "total":1800},
    {"id":"2020", "name":"zooi", "total":1000},
]

I have this code that returns just one object with the result

let result = data.reduce(function (r, o) {
    (r[o.id])?
        r[o.id] += o.total:
        r[o.id] = o.total;
    return r;
});

But I need some like this:

[
    {"id":"2018", "name":"test", "total":1200},
    {"id":"2019", "name":"wath", "total":2300},
    {"id":"2020", "name":"zooi", "total":1000},
]

How can I do it?

like image 284
fernando Avatar asked Dec 10 '22 06:12

fernando


2 Answers

let data =[
    {"id":"2018", "name":"test", "total":1200},
    {"id":"2019", "name":"wath", "total":1500},
    {"id":"2019", "name":"wath", "total":1800},
    {"id":"2020", "name":"zooi", "total":1000},
];

let map = data.reduce((prev, next) =>{
  if (next.id in prev) {
    prev[next.id].total += next.total;
  } else {
     prev[next.id] = next;
  }
  return prev;
}, {});

let result = Object.keys(map).map(id => map[id]);

console.log(result);
like image 53
Zohaib Ijaz Avatar answered Dec 12 '22 18:12

Zohaib Ijaz


You can try this:

const result = Object.values(data.reduce((r, o) => (r[o.id]
  ? (r[o.id].total += o.total)
  : (r[o.id] = {...o}), r), {}));
like image 24
Aravindan Ve Avatar answered Dec 12 '22 20:12

Aravindan Ve