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

Asked

Viewed 176 times

0

I am making an application using firebase and reactjs, which returns an object with the output stream(outflow). As I am using chartjs to display a chart, 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 values and storing the total sum of each month in another array to display on the chart.

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];

1 answer

2


Transform months in an object with 12 properties, one for each month, traverse the array outflow adding the value of the item in the months correspondent

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));

Remark: in your question the outflow owns the month fev and the array months owns the month feb, I believe it was typo, if it was not you will have to do some normalization

  • Interesting approach, I thought it would be like combine map(), filter() and reduce(). Thank you, I will apply in the system and try to arrive at the final result.

  • It’s another possibility, but I think it gets simpler and easier

Browser other questions tagged

You are not signed in. Login or sign up in order to post.