-
Notifications
You must be signed in to change notification settings - Fork 0
/
count_students.js
55 lines (44 loc) · 1.43 KB
/
count_students.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
Alex from Scrimba wants to know how many new students have attended
Scrimba's weekly Town Hall event this year.
He has an array of first-time attendees for each month of the year.
Help him find the total number of attendees! Your function should
take in an array and return a number representing the total number
of new attendees.
Example input: [1,2,3]
Example output: 6
*/
const studentCount = [50, 53, 61, 67, 60, 70, 78, 80, 80, 81, 90, 110];
// 1ST WAY-->
// function sumArray(arr){
// let sum = 0;
// for(let item of arr){
// sum += item; // We are using the for...of loop to iterate over the array. The for...of loop iterates over the values in the array, not the indices.
// }
// return sum;
// }
// console.log(sumArray(studentCount));
// 2ND WAY-->
// function sumArray(arr) {
// let sum = 0;
// for (let i = 0; i < arr.length; i++) {
// sum += arr[i];
// }
// return sum;
// }
// console.log(sumArray(studentCount));
// 3RD WAY -->
// function sumArray(arr){
// // initialize a new variable to hold the sum of the arr
// let sum = 0;
// // loop through the studentCount arr, add each value to the sum
// arr.forEach(item => sum += item);
// // after done looping, return the sum
// return sum;
// }
// console.log(sumArray(studentCount));
// 4TH WAY -->
function sumArray(arr) {
return arr.reduce((sum, item) => sum += item, 0);
}
console.log(sumArray(studentCount));