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

How can I sum contents of array in Javascript?

I have an array called newresult which prints to the console like this:

const newresult = [
  1, 0, 3, 0, 0, 0, 1, 2,
  0, 0, 0, 1, 3, 0, 0, 0,
  0, 0, 0, 2, 0, 0, 0, 3,
  0, 0, 2
];

const sum = [newresult].reduce((partialSum, a) => partialSum + a, 0);
console.log(sum);

The array contents just printing as individual numbers.

Apologies, as I’m sure this is obvious, but what schoolboy error am I making here?

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

Also tried this:

const array1 = [newresult];
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue,
);

Same result:

01,0,3,0,0,0,1,2,0,0,0,1,3,0,0,0,0,0,0,2,0,0,0,3,0,0,2

Thank you

>Solution :

You are putting newresult which is an array by itself inside another array , So inside reduce callback it is basically converting the array to a string and adding 0 to it

const newresult = [
  1, 0, 3, 0, 0, 0, 1, 2,
  0, 0, 0, 1, 3, 0, 0, 0,
  0, 0, 0, 2, 0, 0, 0, 3,
  0, 0, 2
]


const sum = newresult.reduce((partialSum, a) => partialSum + a, 0);
console.log(sum);
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