Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading