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

Use reduce to sum all values of an array passed via a console log

I’m trying to get the total of an array passed via a console log. However instead of adding the numbers it’s returning the array with a 0 in front.

This is what I have tried

const sum2 = (array) => {
  let total = 0;
  const totalFigure = array.reduce((total, number) => {}, 0)
  return total + array
}

console.log(sum2([1, 3, 5, 7, 9]));

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 :

Array.prototype.reduce() accepts callback function where the first parameter of the callback is "total" value calculated in previous iteration of loop and current value of iteration as the second parameter. The final code could look like this:

const sum2 = arr => {
  const result = arr.reduce((total, number) => {
    return total + number;
  }, 0);

  return result;
};

And shorter:

const sum2 = arr => arr.reduce((total, number) => total + number, 0);
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