I have an 'orders' array that looks like this:
[
[
['2022-07-10', 300],
['2022-07-8', 350],
['2022-07-9', 400],
['2022-07-8', 206],
['2022-07-10', 300],
],
[
['2022-07-7', 397],
['2022-07-9', 323],
['2022-07-8', 472],
['2022-07-7', 336],
['2022-07-10', 400],
],
];
what I want at the end is to have an array of objects containing distinct date and total is the sum of element with same dates:
[
{date: '10/07/2022', total: 1000},
{date: '08/07/2022', total: 1028},
{date: '09/07/2022', total: 723},
...
];
Here is what I did and I was wondering if there is a better/shorter way to do that:
groupOrdersByDate(orders: any[]) {
let res: any[] = [];
orders.forEach((ar) => {
ar.forEach((el: any) => {
console.log(res);
let dateOrder: string = new Date(el[0]).toLocaleDateString('fr');
let found = res.some((e) => e.date === dateOrder);
if (!found) {
res.push({ date: dateOrder, total: el[1] });
} else {
let existingObj = res.find((el) => el.date === dateOrder);
let indexx = res.findIndex((o) => {
return o.date === existingObj.date;
});
existingObj.total = existingObj.total el[1];
res.splice(indexx, 1, existingObj);
}
});
});
}
I was also wondering why is my commented console.log of my res array not empty? It shows values even though I did not pushed any elements to it yet ?
CodePudding user response:
It will be more efficient/concise if you store the results in an intermediate object so you don't have to find
match for each element:
const orders = [
[
['2022-07-10', 300],
['2022-07-8', 350],
['2022-07-9', 400],
['2022-07-8', 206],
['2022-07-10', 300],
],
[
['2022-07-7', 397],
['2022-07-9', 323],
['2022-07-8', 472],
['2022-07-7', 336],
['2022-07-10', 400],
],
];
const _sum = {}
orders.forEach(arr => {
arr.forEach(([date, quantity]) => {
let dateOrder = new Date(date).toLocaleDateString('fr');
_sum[dateOrder] = (_sum[dateOrder] ?? 0) quantity;
})
})
let results = Object.entries(_sum).map(([date, total]) => ({date, total}))
console.log(results)