How to sum an array of strings, representing ints

How to sum such an Array [ '', '4490449', '2478', '1280990', '22296892', '244676', '1249', '13089', '0', '0', '0n' ]

If I call something like that ['','4490449', ... , '0n' ].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 🙂

Answer

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', '0n' ];

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/

Leave a Reply

Your email address will not be published. Required fields are marked *