user7302419
user7302419

Reputation:

How to properly sum array in JavaScript

I have a problem to get the sum of my array. I'm using Adwords script, which works like javascript. I can "print out" my array which shows the numbers i'm interested in. Like [23369.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]. But when I'm adding them together using my for-loop the results produce NaN (Not-a-Number). I don't really know what to do.

var spend = [];

function main() {
  var campaignsIterator = AdWordsApp.campaigns().get();
  var sum;

  while(campaignsIterator.hasNext()) {
    var campaigns = campaignsIterator.next();
    var stats = campaigns.getStatsFor("THIS_MONTH");
    var costPerAdG = stats.getCost();

    spend.push(costPerAdG);
  }

  for(var i in spend){
    sum += parseInt(spend[i]);
  }

  Logger.log(spend);
}

Upvotes: 1

Views: 162

Answers (3)

treeseal7
treeseal7

Reputation: 749

here's a simple function for getting the sum of an array

function sumarr(arr){
    return arr.reduce(add, 0);
}

arr=[23369.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

sumarr(arr)

Upvotes: 0

jeffdill2
jeffdill2

Reputation: 4114

You could also define sum and actually sum your array in a single clean one-liner:

var sum = spend.reduce((a, b) => a + b);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386766

You need to initialize sum with 0, otherwise the value is undefined.

If you add a numerical value, you get NaN - if you add a string, then the result is 'undefined' + string.

var sum = 0;
//      ^^^

var a,
    b = 0;

a += 1;
b += 1;
console.log(a); // NaN
console.log(b); // 1 

Upvotes: 2

Related Questions