SirSwish
SirSwish

Reputation: 13

Getting the total value of an array

Hi trying to get the total value from an array (ie Arr[1] + Arr[2] etc) However, I can't seem to figure this out. Here is my current function

this.hourlyTotals = function() {
    var custsperhour = Math.floor(Math.random() * (this.maxcust - this.mincust + 1)) + this.mincust;
    var hourly = custsperhour * this.avgDonuts;
    this.hourlyArray.push(hourly);

    return hourly;

    this.dailyDonuts = function () {
    for (var i = 0; i < 11; i++) {
        var ht = this.hourlyTotals();
        console.log(ht);
        this.dailyTotals += ht;
    }

I'm looking to get the total of each 11 arrays. Any clue?

Upvotes: 0

Views: 71

Answers (2)

posit labs
posit labs

Reputation: 9431

There are a hundred ways to do this. Here are a few.

Built-in method on arrays...

var total = 0,
    arr = [1, 2, 3];
arr.forEach(function(val){ total += val; });

Using underscore...

var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);

http://underscorejs.org/#reduce

Upvotes: 1

Brian
Brian

Reputation: 1553

I'm not sure I totally understand your attempted code, but if you just want to total an array you can do something like this:

var totalArray = function(arr) {
    var result = 0;
    for(var i = 0; i < arr.length; i++) {
        result += arr[i];
    }
    return result;
}

If you had 11 arrays, you could loop over each of them in a similar fashion and call a method like this on all of them.

Upvotes: 1

Related Questions