These forums are now Read Only. If you have an Acrobat question, ask questions and get help from one of our experts.

Sum numbers in an Array ? w/ solution

greenmj
Registered: Aug 21 2006
Posts: 21

How can I sum the numbers in an array? This is what I tried to do

var y = new Array(4)
y[0] = 3;
y[2] = 7 ;
y[1] = 5 ;

var x = this.getField("detail.0") ;
x.value = y[0]+y[1]+y[2]+y[3] ;

// result is NaN

// solved the problem - no empty elements allowed in array
var y = new Array(4)
y[0] = 3;
y[2] = 7 ;
y[1] = 5 ;
y[3] = 0 ;

var x = this.getField("detail.0") ;
x.value = y[0]+y[1]+y[2]+y[3] ;

// result 15

gkaiseril
Online
Expert
Registered: Feb 23 2006
Posts: 4308
Or you can use "isNaN()" function to identify non-numeric and undefined elements in the array. Wrapping this in a callable funciton:

function SumArray(aItem) {
var sum = 0;
for (i = 0; i < aItem.length; i++) {
if ( !isNaN(aItem[i]) ) { //drop NaN items - Not isNaN()
sum += Number(aItem[i]); // add as number
}
return sum; // return the computed sum
}


var y = new Array(4);
y[0] = 3;
y[2] = 7 ;
y[1] = 5 ;

var x = this.getField("detail.0") ;
x.value = SumArray(y);

George Kaiser

gkaiseril
Online
Expert
Registered: Feb 23 2006
Posts: 4308
A more extensive example of the use of "Number()" and "isNaN()" and accessing elements in an array by index number and by active element. Also an example of using test named elements rather than the number index.

var aTable = new Array(12);
aTable[0] = 1;
aTable[2] = 3;
aTable[5] = "a"; // character string
aTable[7] = "4"; // number as a string
aTable["Alpha"] = "Text";
aTable["Number"] = 8;
console.println("Size of aTalbe: " + aTable.length);
var sum = 0;
var sumA = 0;
var sumN = 0;
console.println("by index:");
for (i = 0; i < aTable.length; i++) {
console.println(i + " = " + aTable[i] + " type of: " + typeof aTable[i] + " isNaN: " + isNaN(aTable[i]) );
sum += aTable[i];
if (!isNaN(aTable[i]) ) sumA += Number(aTable[i]);
if (!isNaN(aTable[i]) ) sumN += Number(aTable[i]);
}
console.println("plain sum: " + sum);
console.println("isNaN constricted sum: " + sumA);
console.println("number constricted sum: " + sumN);
console.println("");
console.println("By element:");
sum = 0;
sumA = 0;
sumN = 0;
for (i in aTable) {
console.println(i + " = " + aTable[i] + " type of: " + typeof aTable[i] + " isNaN: " + isNaN(aTable[i]) );
sum += aTable[i];
if (!isNaN(aTable[i]) ) sumA += aTable[i];
if (!isNaN(aTable[i]) ) sumN += Number(aTable[i]);
}
console.println("plain sum: " + sum);
console.println("isNaN constricted sum: " + sumA);
console.println("isNaN & number constricted sum: " + sumN);

George Kaiser