How to sum an array of strings, representing ints

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

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/

Try this:

var sum = 0,
    arr = [ '', '1', '2', '3.0','4\n', '0x10' ],
    i = arr.length;

while( i-- ) {
    // include radix otherwise last element gets interpreted as 16
    sum += parseInt( arr[i], 10 ) || 0; 
}

console.log( sum ) // sum => 10 as 3.0 and 4\n were successfully parsed

Fiddle here

You're correct in using parseInt.

But you need to use it for each of the reduce arguments.

Furthermore, you also need to check if the result of each parseInt is a number, because if not, the function will try to sum a number with NaN and all the other sums will end up being NaN as well.

Mozilla's ECMAscript documentation on parseInt says:

If the first character cannot be converted to a number, parseInt returns NaN.

Then, to avoid getting NaN to spoil your goal, you could implement it like this:

function parseIntForSum(str) {
    var possibleInteger = parseInt(str);
    return isNaN(possibleInteger) ? 0 : possibleInteger;
}

function sum(f, s) {
    return parseIntForSum(f) + parseIntForSum(s);
}

window.alert('sum = ' + [ '', '4490449', '2478', '1280990', '22296892', '244676', '1249', '13089', '0', '0', '0\n' ].reduce(sum)​​​);​

Here's a jsfiddle with it working: http://jsfiddle.net/cLA7c/

You have some values in your array which are not integers. Let's assume they all are, then you can do :

['4490449', '2478', '1280990', '22296892', '244676', '1249', '13089'].reduce( 
    function(t, s) { 
        return parseInt(t) + parseInt(s); 
    }
);

This seems to work ok:

var arry = [ 'asdf', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'ham10am' ];

var res = arry.reduce(function(prev, curr){
    return (Number(prev) || 0) + (Number(curr) || 0);
});

console.log(res); // prints 45