/    Sign up×
Community /Pin to ProfileBookmark

Totals for values in an array

Apologies to everyone if i’ve missed something really obvious.

I have a list of values in an array which have come from a dynamc query. I want to total numbers from one column of the array and display this as the last row of a resulting table.

Can anyone point me at some code to calculate and store the totals?

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@JonaNov 01.2004 — <i>
</i>&lt;script type="text/javascript"&gt;&lt;!--
function addAll(arr){
var newArr = 0;
for(j=0; j&lt;arr.length; j++){
newArr += parseFloat(arr[j]);
}
return newArr;
}

var arrA = ["12.20", "10.04", "15.19", "20.22"];
var arrB = ["3.29", "13.39", "28.93", "1.28"];
document.write('&lt;table&gt;&lt;th&gt;Price1&lt;/th&gt;&lt;th&gt;Price2&lt;/th&gt;&lt;th&gt;Total&lt;/th&gt;');
for(var i=0; i&lt;arrA.length; i++){
if(arrA[i+1]){
document.write('&lt;tr&gt;&lt;td&gt;'+arrA[i]+'&lt;/td&gt;');
document.write('&lt;td&gt;'+arrB[i]+'&lt;/td&gt;&lt;td&gt;');
document.write(parseFloat(arrA[i]+arrB[i]).toFixed(2));
document.write('&lt;/td&gt;&lt;/tr&gt;');
} else {
document.write('&lt;tr&gt;&lt;td&gt;'+addAll(arrA)+'&lt;/td&gt;');
document.write('&lt;td&gt;'+addAll(arrB)+'&lt;/td&gt;&lt;td&gt;');
document.write(parseFloat(addAll(arrA)+addAll(arrB)).toFixed(2));
document.write('&lt;/td&gt;&lt;/tr&gt;');
}
}
document.write('&lt;/table&gt;');
//--&gt;&lt;/script&gt;
×

Success!

Help @agribben spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...