Skip to content

Commit b1db7f8

Browse files
committed
Iteration 3.1 half complete, Iteration 4 complete
1 parent c02cd0e commit b1db7f8

File tree

1 file changed

+36
-6
lines changed

1 file changed

+36
-6
lines changed

src/functions-and-arrays.js

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,22 +33,25 @@ console.log(findLongestWord(words));
3333

3434
// Iteration #3: Calculate the sum
3535
const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10];
36-
let numbersSum = 0;
3736

38-
function sumNumbers(numbers) {
39-
for (let i = 0; i < numbers.length; i++) {
40-
return numbersSum += numbers[i];
37+
38+
function sumNumbers(arrayNumbers) {
39+
let sum = 0;
40+
for (let i = 0; i < arrayNumbers.length; i++) {
41+
sum += arrayNumbers[i];
4142
}
43+
return sum;
4244
}
4345

46+
console.log(sumNumbers(numbers));
4447

4548

4649
// Iteration #3.1 Bonus:
4750
function sum(array) {
4851
let sumArray = 0; //initialize variable for our sum number to store
4952

5053
// Using for loop, iterate through an array; as we do not know how many values inside an array, we need to use array.length;
51-
// code inside the loop is
54+
// code inside the loop: take each array value each itearation and adds it to sumArray variable.
5255
for (let i = 0; i < array.length; i++) {
5356
sumArray += array[i];
5457
}
@@ -61,9 +64,36 @@ console.log(sum([5, 6, 5]));
6164

6265
// Iteration #4: Calculate the average
6366
// Level 1: Array of numbers
67+
68+
// Solution # 1
6469
const numbersAvg = [2, 6, 9, 10, 7, 4, 1, 9];
6570

66-
function averageNumbers() {}
71+
function averageNumbers(array) {
72+
let sumArray = 0;
73+
74+
for (let i = 0; i < array.length; i++) {
75+
sumArray += array[i];
76+
}
77+
return sumArray / array.length;
78+
}
79+
80+
console.log(averageNumbers(numbersAvg));
81+
82+
// Solution # 2
83+
function averageNumbers(array) {
84+
let sumArray = 0;
85+
let count = 0;
86+
87+
array.forEach(function(element){
88+
sumArray += element;
89+
count++;
90+
});
91+
92+
return sumArray / count;
93+
}
94+
95+
console.log(averageNumbers(numbersAvg));
96+
6797

6898

6999
// Level 2: Array of strings

0 commit comments

Comments
 (0)