-4

i have this array :

here is a snippet :

[
  {
    "month": 9,
    "date": "2022-09-01T00:00:00",
    "week_nb": 35,
    "total_Value": 31.356,

  },
  {
    "month": 9,
    "date": "2022-09-17T00:00:00",
    "week_nb": 36,
    "total_Value": 67.726,

  },
  {
    "month": 9,
    "date": "2022-09-08T00:00:00",
    "week_nb": 35,
    "total_Value": 98.63,
  },
  {
    "month": 9,
    "date": "2022-09-24T00:00:00",
    "week_nb": 36,
    "total_Value": 55.178,
   
  },
....

i already specify this by month number

i want to get the sum of TOTALE_VALUE of each WEEK_NB

and store it inside a new array containt 2 objects like

{week_number : X, SumOfTotale_value : X },{week_number : X, SumOfTotale_value : X }...

  • What have you tried so far? – Nitheesh Sep 19 '22 at 09:32
  • Does this answer your question? [Most efficient method to groupby on an array of objects](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects) – B45i Sep 19 '22 at 09:35

1 Answers1

0

You could use Array.reduce() to sum the total value grouped by week.

We'd create an object with a property for each week number, then sum for each matching item.

Object.values() can then be used to convert this object to an array as required.

const input = [ { "month": 9, "date": "2022-09-01T00:00:00", "week_nb": 35, "total_Value": 31.356,  }, { "month": 9, "date": "2022-09-17T00:00:00", "week_nb": 36, "total_Value": 67.726,  }, { "month": 9, "date": "2022-09-08T00:00:00", "week_nb": 35, "total_Value": 98.63, }, { "month": 9, "date": "2022-09-24T00:00:00", "week_nb": 36, "total_Value": 55.178,  } ] 

const result = Object.values(input.reduce((acc, { week_nb, total_Value }) => { 
    acc[week_nb] = acc[week_nb] || { week_number: week_nb, SumOfTotale_value: 0 };
    acc[week_nb].SumOfTotale_value += total_Value;
    return acc;
}, {}));

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

You can also use a for..of loop to get the same result:

const input = [ { "month": 9, "date": "2022-09-01T00:00:00", "week_nb": 35, "total_Value": 31.356,  }, { "month": 9, "date": "2022-09-17T00:00:00", "week_nb": 36, "total_Value": 67.726,  }, { "month": 9, "date": "2022-09-08T00:00:00", "week_nb": 35, "total_Value": 98.63, }, { "month": 9, "date": "2022-09-24T00:00:00", "week_nb": 36, "total_Value": 55.178,  } ] 

const map = {};

for(let { week_nb, total_Value } of input) {
    map[week_nb] = map[week_nb] || { week_number: week_nb, SumOfTotale_value: 0 }
    map[week_nb].SumOfTotale_value += total_Value;
}

console.log('Result:', Object.values(map))
.as-console-wrapper { max-height: 100% !important; }
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40