Using Reduce method in an exercise

Hello everyone, I’ve been studyng JS and doing some exercices but I’m having a little trouble using reduce.

I got this array:

const installments = [
{ installment_number: 1, value: 123.45, status: ‘Paid’ },
{ installment_number: 2, value: 139.88, status: ‘Paid’ },
{ installment_number: 3, value: 123.45, status: ‘Paid’ },
{ installment_number: 4, value: 182.37, status: ‘Open’ },
{ installment_number: 5, value: 133.93, status: 'Open },
]

One of the exercises ask me to print an object with the value for total paid and total open: {total_paid: 386.78, total_open: 316.3}

I got here so far and got stuck, could you help me please

const total = installments.reduce((acc, elem) => {

console.log(‘total_paid:’, acc.value, ‘total_open:’, elem.value)

return acc + elem

}, 0)

1 Like

Hi @possiblevivi, since the result should be an object you’d use an object of the desired shape as initial value:

const total = installments.reduce((acc, elem) => {
  // ...
}, { 
  total_paid: 0, 
  total_open: 0 
})

Then inside the function, check if elem is paid or open, and add to the corresponding accumulator property:

const total = installments.reduce((acc, elem) => {
  if (elem.status === 'Paid') {
    acc.total_paid += elem.value
  } else {
    acc.total_open += elem.value
  }

  return acc
}, { 
  total_paid: 0, 
  total_open: 0 
})

Or maybe a bit more consisely:

const total = installments.reduce((acc, elem) => {
  const prop = elem.status === 'Paid' 
    ? 'total_paid' 
    : 'total_open'

  acc[prop] += elem.value

  return acc
}, { 
  total_paid: 0, 
  total_open: 0 
})
2 Likes

Hi @m3g4p0p thank you for your help, your explanation was very clear :raised_hands:

2 Likes

My pleasure. :-)