JavaScript
x
6
1
const grades = [9, 8, 5, 7, 7, 4, 9, 8, 8, 3, 6, 8, 5, 6];
2
for (let i = 0; i < grades.length; i++) {
3
if (grades[i] >= 8) {
4
console.log(grades[i])
5
}
6
}
I’m trying to log how many items from the array fulfil the condition. the output I’m looking for is : 6 (because 6 of the numbers are equal or greater than 8)
tried
let count = 0; for (let i = 0; i < grades.length; i++) {
if (grades[i]>= 8){ count++
JavaScript
1
4
1
console.log(count)
2
3
}
4
}
Advertisement
Answer
JavaScript
1
16
16
1
function countGreaterThan8(grades){
2
// initialize the counter
3
let counter = 0;
4
for (let i = 0; i < grades.length; i++) {
5
6
// if the condition satisfied counter will be incremented 1
7
if (grades[i] >= 8) {
8
counter++;
9
}
10
}
11
return counter;
12
}
13
14
const grades = [9, 8, 5, 7, 7, 4, 9, 8, 8, 3, 6, 8, 5, 6];
15
console.log(countGreaterThan8(grades)); // 6
16