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

  1. Start with scores: [1, 3, 5, 7, 9].
  2. filter checks one score at a time.
  3. Scores that pass the test are copied into passing.
  4. 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