Chain filter, map, and reduce over an array.

Array Methods

array_methods.js
const threshold = 2;
const nums = [1, 2, 3, 4, 5];
const kept = nums.filter((n) => n > threshold);
const doubled = kept.map((n) => n * 2);
const sum = doubled.reduce((acc, n) => acc + n, 0);

console.log("kept=" + kept.join(","));
console.log("sum=" + sum);

Follow the Chain

  1. threshold starts as 2.
  2. filter keeps values greater than 2: 3, 4, and 5.
  3. map doubles those kept values into 6, 8, and 10.
  4. reduce adds the doubled values.
  5. The script prints kept=3,4,5 and sum=24. | step | values | | --- | --- | | start | 1,2,3,4,5 | | after filter | 3,4,5 | | after map | 6,8,10 | | after reduce | 24 |
array-methods `filter` keeps matching elements, `map` transforms each one, and `reduce` combines them into a single value, here a sum.

Exercise: array_methods.js

Reproduce kept=3,4,5 and sum=24, then use the pinned threshold variants 3 and 5 to predict kept=4,5 sum=18 and kept= sum=0.