0

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 ?

1
  • 1
    1) Your code seems readable to me, this should be ok. 2) I was also wondering why is my commented console.log of my res array not empty? Console values are passed as reference, hence you are seeing the recent values of res. Commented Aug 14, 2022 at 0:13

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.