-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaverageGrade.js
More file actions
36 lines (25 loc) · 1.22 KB
/
averageGrade.js
File metadata and controls
36 lines (25 loc) · 1.22 KB
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
// It's the academic year's end, fateful moment of your school report. The averages must be calculated. All the students come to you and entreat you to calculate their average for them. Easy ! You just need to write a script.
// Return the average of the given array rounded down to its nearest integer.
// The array will never be empty.
// getAverage([2,2,2,2]),2)
// getAverage([1,2,3,4,5,]),3);
// getAverage([1,1,1,1,1,1,1,2]),1)
function getAverage(grades) {
if (grades.length === 0) return 0; //if the array is empty, return 0 --> edge case
let total = 0;
for (let i = 0; i < grades.length; i++) {
total += grades[i];
}
return Math.floor(total / grades.length); // round down
}
// Use array.reduce(), divided by array.length and put into Math.floor
function getAverage(grades) {
const total = grades.reduce((sum, grade) => sum + grade, 0);
return Math.floor(total / grades.length);
}
// .reduce() loops through the array and adds up all the values.
// sum is the accumulator, and grade is the current item.
// 0 is the initial value of the accumulator.
getAverage([2, 2, 2, 2]); // returns 2
getAverage([1, 2, 3, 4, 5]); // returns 3
getAverage([1, 1, 1, 1, 1, 1, 1, 2]); // returns 1