Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript, Using a for loop to calculate the sum of all the values within an array

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>
like image 444
CChristiansen Avatar asked Dec 06 '22 14:12

CChristiansen


2 Answers

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

like image 123
Nishi Gaba Avatar answered Apr 19 '23 23:04

Nishi Gaba


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));
like image 21
Richard.Davenport Avatar answered Apr 19 '23 23:04

Richard.Davenport