John Smith
John Smith

Reputation: 101

Add all values in an array JavaScript/jquery

<div id="timeCalac">Click me to calculate your average time</div>
myData = [34, 67, 78];
var arrayTotalValue = 0;

$("#timeCalac").click(function () {
    // arrayTotalValue = add value of myData array function
    arrayTotalValue = arrayTotalValue/myData.length;
    $("#timeCalac").html(arrayTotalValue);    
});

I am making a function that records how long it took for the user to click on a element I then use the .push() command to add this number to the myData array. Is there a JavaScript or jQuery function that can add the value of the myData array and then store it in the arrayTotalValue variable.

Upvotes: 0

Views: 1537

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

There is no specific function to sum the values of an array, however you can use reduce() to achieve it:

myData = [34, 67, 78];
var arrayTotalValue = 0;

$("#timeCalac").click(function () {
    arrayTotalValue = myData.reduce(function(a, b) {
        return a + b;
    });
    $(this).html(arrayTotalValue);    
});

Upvotes: 1

Related Questions