Higher-Order Array Methods
Filtering Values
Keep only the array elements that match a test.
Filtering Values
filter_values.js
const minimum = 4;
const scores = [1, 3, 5, 7, 9];
const passing = scores.filter((score) => score >= minimum);
console.log("minimum=" + minimum);
console.log("passing=" + passing.join(","));
Keep or Drop
- Start with
scores:[1, 3, 5, 7, 9]. filterchecks one score at a time.- Scores that pass the test are copied into
passing. - Scores that fail the test are left out.
| Score |
score >= minimum| Result | | --- | --- | --- | |1| false | drop | |5| true | keep | |9| true | keep |
filter-values
`filter` returns a new array containing only elements whose callback returns `true`.
Exercise: filter_values.js
Use filter to keep scores at or above a minimum and print the kept values