Counting
The second pattern counts: how many elements of an array meet a condition? It looks like adding up, but instead of the value, you add 1, and only when an if says so:
const temperatures = [18, 24, 27, 15, 31, 22, 29];
let hotDays = 0;
for (const temperature of temperatures) {
if (temperature >= 25) {
hotDays++;
}
}
console.log("Hot days:", hotDays);Hot days: 3The counter hotDays starts at 0, before the loop. The loop looks at every temperature, and the if decides whether to count it. hotDays++ runs only for 27, 31 and 29, so at the end, the counter is 3. Again, you print the result after the loop.
Sometimes you want to know not only how many, but also which ones. Then start with an empty array and .push() each matching element into it:
const temperatures = [18, 24, 27, 15, 31, 22, 29];
const hot = [];
for (const temperature of temperatures) {
if (temperature >= 25) {
hot.push(temperature);
}
}
console.log("Hot temperatures:", hot);
console.log("Hot days:", hot.length);Hot temperatures: [27, 31, 29]
Hot days: 3The array hot can be a const: you add elements to it, but you never store a different array in the variable.
Instructions
- 1
The array
scoresholds the points from a test. You pass with 50 points or more. Count the students who passed: create a variablepassedwith the value0, go throughscoreswith a loop, and for every score of at least 50, increasepassedby one with++. After the loop, printconsole.log("Passed:", passed);. The output isPassed: 5. - 2
Now also collect the scores below 50: before the loop, create an empty array
failed, and inside the loop, add each score below 50 to it with.push()(anelsewill do). After the loop, print it withconsole.log("Failed:", failed);. The output isFailed: [45, 38, 29].