Voici à quoi ressemble l'aggregation dans une base de données !
const products = [
{
"_id": 1,
"item": "abc",
"price": 10,
"quantity": 2,
"date": "2014-03-01T08:00:00.000Z"
},
{
"_id": 2,
"item": "jkl",
"price": 20,
"quantity": 1,
"date": "2014-03-01T09:00:00.000Z"
},
{
"_id": 3,
"item": "xyz",
"price": 5,
"quantity": 10,
"date": "2014-03-15T09:00:00.000Z"
},
{
"_id": 4,
"item": "xyz",
"price": 5,
"quantity": 20,
"date": "2014-04-04T11:21:39.736Z"
},
{
"_id": 5,
"item": "abc",
"price": 10,
"quantity": 10,
"date": "2014-04-04T21:23:13.331Z"
},
{
"_id": 6,
"item": "def",
"price": 7.5,
"quantity": 5,
"date": "2015-06-04T05:08:13.000Z"
},
{
"_id": 7,
"item": "def",
"price": 7.5,
"quantity": 10,
"date": "2015-09-10T08:43:00.000Z"
},
{
"_id": 8,
"item": "abc",
"price": 10,
"quantity": 5,
"date": "2016-02-06T20:20:13.000Z"
}
]
const groupBy = (arr, key) =>
arr.reduce((acc, i) => {
(acc[i[key]] = acc[i[key]] || [] ).push(i);
return acc;
}, {});
let result = [];
let items = groupBy(products,"item");
for (const [key, value] of Object.entries(items)) {
// console.log(`${key}, ${value}`);
result.push(
{
"_id": key,
"totalSaleAmount": value.reduce(function(acc, cur) {
acc+=cur.price*cur.quantity;
return acc
},0)
}
)
}
//console.table(result)
console.log(result)