I just starting using JavaScript a couple weeks ago and still struggling a bit. I need to create a loop that calculates the sum of all values coming from a votes array in a separate .js file.
The function has a single parameter, votes, representing one of the five vote arrays (vote1 through vote5). Add the following commands to the function:
a. Declare a variable named total, setting its initial value to 0.
b. Create a for loop that loops through each of the items in the votes array, adding that item’s value to the total variable.
c. After the for loop is completed, return the value of the total variable from the function.
Heres my html file.
<script>
function totalVotes()
{
var total = 0;
for (i=0; i < votes.length; ++i)
{
total += votes[i];
}
return total;
}
</script>
You can use reduce Method of array. Reduce Method gives concatenated value based on elements across the Array. For Example :
const sum = [1,2,3].reduce(function(result,item) {
return result + item;
}, 0);
console.log(sum);
The above code gives the output 6 that is the sum of given array. You can check other methods of array on my Gist: Iterate_Over_Array.js
You just need to pass in the array you want to iterate over:
var vote1 = [45125, 44498, 5143]
function totalVotes(votes) {
var total = 0;
for (var i = 0; i < votes.length; i++) {
total += votes[i];
}
return total;
}
// better alternative
function tallyVotes(votes) {
return votes.reduce((total, vote) => total + vote, 0);
}
console.log('for loop: ', totalVotes(vote1));
console.log('reduce: ', tallyVotes(vote1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With