Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
rymatech
4,671 PointsHow do you find the sum of every number within an array?
For example:
var numbers = [1, 2, 3, 4];
would equal 10.
var temperatures = [100,90,99,80,70,65,30,10];
for (var i = 0; i < temperatures.length; i++) {
var temp = temperatures[i];
}
I am currently trying to build a function which finds the average of an array.
3 Answers
andren
28,558 PointsThere are various ways of doing it. The simplest way that does not rely on any functions or techniques you have likely not come across yet (like reduce) is to loop over the list like this:
var numbers = [1, 2, 3, 4]; // Initialize numbers variable
var sum = 0; // Initialize sum variable
for (var i = 0; i < numbers.length; i++) { // Loop once for each item in the list
sum += numbers[i]; // Uses the counter of the loop to pull out items from the list
}
console.log(sum); // Will print out 10
Since the counter for the loop (the i variable) will start at 0 and go up by one each time the loop runs it can be used to pull out each item from the list. The first time it runs it will pull out the item at index 0 (the first item), the second time the loop runs it will pull out the item at index 1 (the second item) and so on.
If you are still confused, or feel that my explanation was unclear, then feel free to reply with followup questions. I'll gladly answer anything I can.
rymatech
4,671 PointsPerfect, completely understand, thanks for your help.
Ari Misha
19,323 PointsHiya there! It can be done in a single line of code with the reduce method in the Array.prototype. Here how it can be done:
const arr = [1, 2, 3, 4, 5, 6];
arr.reduce((num, acc) => num + acc); //21
I hope it helps!
~ Ari ~