Suppose you want to do group by on object array then we can use underscore.js
I have object array x which has keys amount,date & valid.I want to do sum of amount based on date key and use only those record which are valid as 1.
Here is example code
var _ = require('underscore');
var x=[
{
"date":"2021-04-14",
"amount":1300,
"valid":1
},
{
"date":"2021-05-14",
"amount":700,
"valid":0
},
{
"date":"2021-06-13",
"amount":2300,
"valid":1
},
{
"date":"2021-07-10",
"amount":1000,
"valid":0
},
{
"date":"2021-07-10",
"amount":1300,
"valid":1
},
{
"date":"2021-04-14",
"amount":1700,
"valid":1
}
]
x = x.filter((m)=>{
return m.valid==1
})
console.log("Filtered",x);
var grouped = _.groupBy(x, 'date');
console.log("group by date:",grouped);
var result=[];
for (const key in grouped) {
var sum = grouped[key].reduce((accumulator,a)=>{
return accumulator + a.amount
},0);
result.push({
"date":key,
"amount":sum
})
}
console.log("result:",result);
Output:
Filtered [
{ date: '2021-04-14', amount: 1300, valid: 1 },
{ date: '2021-06-13', amount: 2300, valid: 1 },
{ date: '2021-07-10', amount: 1300, valid: 1 },
{ date: '2021-04-14', amount: 1700, valid: 1 }
]
group by date: {
'2021-04-14': [
{ date: '2021-04-14', amount: 1300, valid: 1 },
{ date: '2021-04-14', amount: 1700, valid: 1 }
],
'2021-06-13': [ { date: '2021-06-13', amount: 2300, valid: 1 } ],
'2021-07-10': [ { date: '2021-07-10', amount: 1300, valid: 1 } ]
}
result: [
{ date: '2021-04-14', amount: 3000 },
{ date: '2021-06-13', amount: 2300 },
{ date: '2021-07-10', amount: 1300 }
]
No comments:
Post a Comment