How to sum an array of strings, representing ints

11,055

Solution 1

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/

Solution 2

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

Solution 3

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

Solution 4

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/

Share:
11,055
zzeroo
Author by

zzeroo

I don't like IT, but IT likes me. At the moment I'm working as an full stack developer for embedded systems. I build software for all kinds of ARM and PIC Microchip controller. The weapons of my choice are Rust and C. But I also create, deploy and maintains projects in Ruby on Rails with a highly focus on the PostgreSQL database.

Updated on June 27, 2022

Comments

  • zzeroo
    zzeroo almost 2 years

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