Search code examples
javascriptreduce

Count with reduce


I have the current code (snippet) but I want to count the total of the answers

Example:

"2022-01-03": {
    "yes": 1,
    "no": 2,
    "total": 3
  }

const array = [
  { date: '2022-01-03', answer: 'yes' },
  { date: '2022-01-03', answer: 'no' },
  { date: '2022-01-03', answer: 'no' },
  { date: '2022-01-04', answer: 'yes' },
  { date: '2022-01-04', answer: 'yes' },
  { date: '2022-01-05', answer: 'yes' },
  { date: '2022-01-05', answer: 'yes' },
  { date: '2022-01-05', answer: 'yes' },
  { date: '2022-01-05', answer: 'no' },
]

const result = array.reduce((acc, curr) => {
  if (!acc[curr.date]) {
    acc[curr.date] = { yes: 0, no: 0 }
  }
  acc[curr.date][curr.answer]++;
  return acc;
}, {});

console.log(result)

What is the correct way to do it?


Solution

  • You can add a total field and increment for every value:

    const array = [
      { date: '2022-01-03', answer: 'yes' },
      { date: '2022-01-03', answer: 'no' },
      { date: '2022-01-03', answer: 'no' },
      { date: '2022-01-04', answer: 'yes' },
      { date: '2022-01-04', answer: 'yes' },
      { date: '2022-01-05', answer: 'yes' },
      { date: '2022-01-05', answer: 'yes' },
      { date: '2022-01-05', answer: 'yes' },
      { date: '2022-01-05', answer: 'no' },
    ]
    
    const result = array.reduce((acc, curr) => {
      if (!acc[curr.date]) {
        acc[curr.date] = { yes: 0, no: 0, total: 0 }
      }
      acc[curr.date][curr.answer]++;
      acc[curr.date].total++;
      return acc;
    }, {});
    
    console.log(result)
    .as-console-wrapper { max-height: 100% !important; }