Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
185
rated 0 times [  189] [ 4]  / answers: 1 / hits: 7467  / 7 Years ago, thu, february 2, 2017, 12:00:00

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?


More From » arrays

 Answers
3

You have to use parseInt (if the numbers are Integers), parseFloat (if they are Floats) or Number (if not sure) to explicitly interpret them as numbers like:



sum = tot.reduce((a, n) => (a + Number(n)), 0);

[#23129] Wednesday, February 1, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mary

Total Points: 432
Total Questions: 98
Total Answers: 98

Location: Luxembourg
Member since Tue, Jan 25, 2022
2 Years ago
;