simplify javascript count

Hi,

I’m creating a total count in my datamapper, but this is alot of repetitive scripting which I think can be much compacter.

This is a sample of the code:

var counter = parseInt(record.tables[“detail”][steps.currentLoopCounter - 1].fields[“count1”]);

if(!isNaN(counter)){

dagTotaal += counter;

}

counter = parseInt(record.tables[“detail”][steps.currentLoopCounter - 1].fields[“count2”]);

if(!isNaN(counter)){

dagTotaal += counter;

}

I need to add twenty of these addupps.

Is there a way to simplify this code?

thank you in advance.

Perfect spot to use JavaScript’s array.reduce method:

var flds = ['count1,'count2','count3','count4']; // add all field names here
flds.reduce( function(accumulator, currentValue) {
   return accumulator + (data.extract(currentValue,0)*1);
},0);

You’ll have to adapt to your own needs but that’s the gist of it. You can read up on reduce() here: Array.prototype.reduce() - JavaScript | MDN


 

Hi Phil,

Thank you, I didn’t use your script, but I solved it with the workflowplugin.

I also had some difficulties to fill the variable as the were in the detail table. the datamapper kept giving me an error.

var flds = [[record.tables["detail"][index].fields["count1"],record.tables["detail"][index].fields["count2"]]; // add all field names here
flds.reduce( function(accumulator, currentValue) {
   return accumulator + (data.extract(currentValue,0)*1);
},0);

I think you could simply have used:

var flds = ["count1","count2"];
flds.reduce( function(accumulator, currentValue) {
   return accumulator + (record.tables["detail"][index].fields[currentValue]*1);
},0);

In any event, if you found a working solution, then by all means keep it! :slight_smile:

thank you for your help,

I’m still learning each day about javascript so this is also helpfull in the future.