How to sum an array of strings, representing ints

arrays, casting, javascript, node.js

Solution

You need to assure that the values you are summing are integers. Here's one possible solution:

var ary=[ '', '4490449', '2478', '1280990', '22296892', 
          '244676', '1249', '13089', '0', '0', '0\n' ];

console.log(
  ary
    .map( function(elt){ // assure the value can be converted into an integer
      return /^\d+$/.test(elt) ? parseInt(elt) : 0; 
    })
    .reduce( function(a,b){ // sum all resulting numbers
      return a+b
    })
)​;

which prints '28329823' to the console.

See fiddle at http://jsfiddle.net/hF6xv/

Problem

How to sum such an Array ` [ '', '4490449', '2478', '1280990', '22296892', '244676', '1249', '13089', '0', '0', '0\n' ] ` If I call something like that `['','4490449', ... , '0\n' ].reduce(function(t,s){ return t+s)` on that array, the stings are joined and not summed. I've tried some casting with `parseInt()` but this results in `NaN` :)

Original source