Make sum of the values of each equal item, stored in one object and store in another array

0

I am making an application using firebase and reactjs, which returns an object with the outflow. Since I am using chartjs to display a graph, I need to generate an array where each position would have the total sum for each month. My difficulty is being to go through this object for each month, calculating the total of the values and storing the total sum of each month in another array to present in the graph.

const outflow = {
  '-LNpeDWzApnfSjHEJdh': {
    date: '2018-01-10',
    month: 'jan',
    name: 'Valter',
    value: 200,
  },
  '-LNpeDWzApnfSjFHlPJq': {
    date: '2018-02-02',
    month: 'fev',
    name: 'Antônio ',
    value: 250,
  },
  '-LOOg_bniqNre4xMDKN6': {
    date: '2018-01-20',
    month: 'jan',
    name: 'Bento',
    value: 200,
  },
  '-LOOg_bniheke4xMDK44': {
    date: '2018-02-22',
    month: 'fev',
    name: 'Jhon Due',
    value: 250,
  },
};

const months = [
  'Jan',
  'Feb',
  'Mar',
  'Apr',
  'May',
  'Jun',
  'Jul',
  'Aug',
  'Sep',
  'Oct',
  'Nov',
  'Dez',
];

// O resultado que preciso, seria parecido com o array abaixo. 
// Onde armazenaria na primeira posição a soma total dos valores
// referente a Janeiro, segundo Fevereiro e assim por diante.

let sumValuesMonth = [400, 500];
    
asked by anonymous 09.10.2018 / 21:51

1 answer

2

Transform months into an object with 12 properties, one for each month, cycle through the outflow array by adding the value of the item to the corresponding months property

const outflow = {
  '-LNpeDWzApnfSjHEJdh': {
    date: '2018-01-10',
    month: 'jan',
    name: 'Valter',
    value: 200,
  },
  '-LNpeDWzApnfSjFHlPJq': {
    date: '2018-02-02',
    month: 'feb',
    name: 'Antônio ',
    value: 250,
  },
  '-LOOg_bniqNre4xMDKN6': {
    date: '2018-01-20',
    month: 'jan',
    name: 'Bento',
    value: 200,
  },
  '-LOOg_bniheke4xMDK44': {
    date: '2018-02-22',
    month: 'feb',
    name: 'Jhon Due',
    value: 250,
  },
};

const months = {
  jan: 0,
  feb: 0,
  mar: 0,
  apr: 0,
  may: 0,
  jun: 0,
  jul: 0,
  aug: 0,
  sep: 0,
  oct: 0,
  nov: 0,
  dez: 0,
};

for (key in outflow) {
  months[outflow[key].month] += parseInt(outflow[key].value);
}

document.write(JSON.stringify(months));

Note: In your question, the outflow has the month fev and the months array has the month feb , I believe it was a typo, otherwise there was some normalization

    
09.10.2018 / 22:07