I'm having a php json_encode object fetched by ajax. whet I want to do is to sum this array. Here's what I did so far:
var json = $.parseJSON(data);
var tot = new Array();
for (var i = 0; i < json.length; ++i) {
tot.push(json[i].final_total);
$('table tbody').append("<tr><td>" + json[i].order_id + "</td><td>" + json[i].final_total + "</td></tr>");
}
Now I want to sum this array. I tried this:
var sum = tot.reduce(function(pv, cv) { return pv + cv; }, 0);
$("#total").html( sum );
But the result is:
09.748.529.129.129.119.59.79.89.79.89.79.79.79.79.79.79719.248.59.79 ......
I also tried:
myFunction(tot);
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("total").innerHTML = item.reduce(getSum);
}
But I got the same result above (Numbers written next to each other).
I also tried this:
var tot = 0;
for (var i = 0; i < json.length; ++i) {
tot += json[i].final_total);
$('table tbody').append("<tr><td>" + json[i].order_id + "</td><td>" + json[i].final_total + "</td></tr>");
}
$("#total").html( tot );
But I got the same result above (Numbers written next to each other).
So what is the proper way to sum an array in javascript?
Array elements are
strings
, in order to properly add them, they have to be casted tointeger
:Taken from MDN:
The is a common issue caused by
+
operator used for both string concatenation and addition. Issue is best described with following example:Edit: @Pointy - Nice catch, thanks! :)
you will need to use a parse int because its concatenating the sting instead of adding integers
parseInt
You have to use
parseInt
(if the numbers are Integers),parseFloat
(if they are Floats) orNumber
(if not sure) to explicitly interpret them as numbers like: