Search code examples
javascriptarraysobject

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?

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