 |
Subtotal array
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...
On May 23, 6:35 pm, moua@yahoo.com wrote: > 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"))
On May 23, 6:00 pm, "scripts.contact" <scripts.cont@gmail.com> wrote:
> On May 23, 6:35 pm, moua @yahoo.com wrote:> 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"))
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[i][field1]==grp){ sum+=Number(this[i][field2].toString().replace(/\$|\,/g,'')) || 0; } } return sum;
}
|
 |