Subtotal array

M

mouac01

I have this array:

[{"acct":"A1","dr":100,"cr":100},{"acct":"A2","dr":200,"cr":200},
{"acct":"A1","dr":300,"cr",300},{"acct":"A2","dr":400,"cr",400}]

How would I get the subtotal of each acct so that total for A1 dr/cr
is 400 and total for A2 dr/cr is 600.
TIA...
 
S

scripts.contact

I have this array:

[{"acct":"A1","dr":100,"cr":100},{"acct":"A2","dr":200,"cr":200},
{"acct":"A1","dr":300,"cr",300},{"acct":"A2","dr":400,"cr",400}]

How would I get the subtotal of each acct so that total for A1 dr/cr
is 400 and total for A2 dr/cr is 600.
-----
function getTotal(arr,acc){
var i=0,n,drtotal=0,crtotal=0;
while(n=arr[i++])
if(n.acct==acc){
drtotal+=n.dr
crtotal+=n.cr
}
return [drtotal,crtotal]
}

-----

Example:
d=[{"acct":"A1","dr":100,"cr":100},{"acct":"A2","dr":200,"cr":200},
{"acct":"A1","dr":300,"cr":350},{"acct":"A2","dr":400,"cr":400}]
alert(getTotal(d,"A1"))
 
M

mouac01

[{"acct":"A1","dr":100,"cr":100},{"acct":"A2","dr":200,"cr":200},
{"acct":"A1","dr":300,"cr",300},{"acct":"A2","dr":400,"cr",400}]
How would I get the subtotal of each acct so that total for A1 dr/cr
is 400 and total for A2 dr/cr is 600.

-----
function getTotal(arr,acc){
var i=0,n,drtotal=0,crtotal=0;
while(n=arr[i++])
if(n.acct==acc){
drtotal+=n.dr
crtotal+=n.cr
}
return [drtotal,crtotal]
}

-----

Example:
d=[{"acct":"A1","dr":100,"cr":100},{"acct":"A2","dr":200,"cr":200},
{"acct":"A1","dr":300,"cr":350},{"acct":"A2","dr":400,"cr":400}]
alert(getTotal(d,"A1"))

Thanks for your help.
I've decided to use this:

Array.prototype.subtotal=function(grp,field1,field2){
for(var i=0,sum=0;i<this.length;i++){
if(this[field1]==grp){
sum+=Number(this[field2].toString().replace(/\$|\,/g,'')) || 0;
}
}
return sum;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,427
Latest member
HildredDic

Latest Threads

Top