parsing numbers in a javascript array

Choy picture Choy · Apr 5, 2010 · Viewed 16.2k times · Source

Hi I have a string of numbers separated by commas, "100,200,300,400,500" that I'm splitting into an array using the javascript split function:

var data = [];
data = dataString.split(",");

I'm trying to parse the values of the array using parseFloat and then store them back into the array. I'd then like to add up the numbers in the array and store it as another variable, "dataSum".

I've got the following code, but I can't get it working:

var dataSum = "";

for (var i=0; i < data.length; i++) {
    parseFloat(data[i]);
    dataSum += data[i];
}

So at the end of all this, I should be able to access any of the parsed numbers individually data[0], data[1], etc... and have a total number for dataSum. What am I doing wrong?

Answer

kennytm picture kennytm · Apr 5, 2010

(1)

var dataSum = "";

You are initializing dataSum as a string. For strings, the += is a concatenation operator, so you'll get 100200300400500 because of concatenation. You should initialize it to 0:

var dataSum = 0;

(2)

parseFloat does not modify the input parameter. The float value is returned. So you should use

dataSum += parseFloat(data[i]);

(3)

var data = [];
data = dataString.split(",");

The 2nd assignment will override the 1st. Just write

var data = dataString.split(",");

(BTW, ECMAScript 5 supports this one-liner:

return "100,200,300,400,500".split(/,/).map(parseFloat).reduce(function(x,y){return x+y;})

)