0
<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.

1 Answer 1

1

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);    
});
Sign up to request clarification or add additional context in comments.

5 Comments

How can I get the return value of this function then store it in my arrayTotalValue variable?
@JohnSmith that's what this is doing...?
How do I put it in a variable tho? I am new to all this
It is in a variable - the arrayTotalValue variable.
Here's a working example to hopefully make it more clear: jsfiddle.net/sd6Lwuny

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.