Home > Blockchain >  Count with reduce
Count with reduce

Time:07-11

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?

CodePudding user response:

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

CodePudding user response:

I didn't see any problem in your code, but I shortened one line and it became more optimized.

From:

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

to

const result = array.reduce((acc, curr) => {
  acc[curr.date] ||= { yes: 0, no: 0, total: 0 };
  acc[curr.date][curr.answer]  ;
  acc[curr.date][total]  
  return acc;
}, {});
  • Related