Home > Enterprise >  How to calculate sum of multiple responses inside a loop using javascript?
How to calculate sum of multiple responses inside a loop using javascript?

Time:05-21

I have two loops as shown:

        for (var i = 0; i < nearPlacements.length; i  ) {
           var meshInstances = nearPlacements[i].model.model.meshInstances;
var mat;
var matEach = 0;
for (var i2 = 0; i2 < meshInstances.length; i2  ) {
    mat = parseFloat(meshInstances[i2].mesh.indexBuffer[0].numIndices / 3);
    matEach  = mat;
    }
    console.log(matEach);
}

console.log(matEach); outputs data as:

enter image description here

How to display data as a sum of all responses? Thanks

CodePudding user response:

its like what you did with matEach variable but outside outer loop.

let total = 0;
for (var i = 0; i < nearPlacements.length; i  ) {
  var meshInstances = nearPlacements[i].model.model.meshInstances;
  var mat;
  var matEach = 0;
  for (var i2 = 0; i2 < meshInstances.length; i2  ) {
    mat = parseFloat(meshInstances[i2].mesh.indexBuffer[0].numIndices / 3);
    matEach  = mat;
  }
  console.log(matEach);
  total  = matEach;
}

console.log(total);
  • Related