When it comes to working with arrays, leveraging methods like filter
and map
can simplify the process by automatically looping through each item in the array and returning a new array based on certain conditions. This eliminates the need for manual iteration using a for
loop.
Instead of writing:
for(i = 0; i < grades.length; i++) {
for(i = 0; i < grades.length; i++) {
if(grades[i] > 70) {
...
}
}
}
We can simply achieve the same result by filtering the grades array directly and returning only the elements that meet our condition. In this case, we can just return
the result of grades.filter
.
It's important to note that the function passed into .filter
will be executed on each item in the array. So instead of referencing each item using grades[i]
, you can use a more descriptive variable like grade
to make your code clearer.
In essence, we are telling the array to filter itself based on a specific condition (in this case, grades greater than or equal to 70), and return a new array with only the filtered items.
var passingGrades = function(grades) {
return grades.filter(function(grade) {
return grade >= 70;
});
}
console.log( passingGrades([63, 75, 39, 88, 94, 100, 24]) );