Skip to content
Advertisement

JavaScript – Adding the totals in Array with same index

I have moved on to learning about looping over arrays and hit a hurdle – did try researching but I think I am probably not describing properly…

I have managed to total each line in the array. I did create another variable called total but not sure I needed that…

I get the output below, which all seem to occupy index 0 – think I have confused myself here 🙂

JavaScript

Now I want to add these values. -Any pointers would be most welcome.

JavaScript

Advertisement

Answer

Rather than using three separate function calls, I suggest you use one, and pass through a 2d array (an array that contains other arrays):

JavaScript

You can now create two separate functions. The first function is responsible for summing the numbers in a nested array (eg: [17, 2, 3] gives 22), and another for looping over each array you want to sum, and adding that to a total. You have already made the first function (although, as you mentioned, the total variable that stores an array isn’t needed, so this can be removed for this approach)

JavaScript

The next step is to create a second function, that will loop through an array of arrays (so each element within your array is an array itself):

JavaScript

The above can be written by using nested loops, but using functions to decompose your logic can help with clarity. You can use separate function calls though if you use a closure (ie: create a total sum in your function and return a function that is responsible for adding to that total). If you’re a beginner, I suggest the first approach as it’s more straightforward:

JavaScript

Finally, you can use array methods, such as .reduce() to make your code more concise. Using .reduce() hides an internal loop behind a method call, which allow you to “reduce” the values in your array into another/transformed value (in this case, your sum):

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement