Chain filter, map, and reduce over an array.

array-methods `filter` keeps matching elements, `map` transforms each one, and `reduce` combines them into a single value, here a sum.

Array Methods

threshold
array_methods.js
Replay: real traced execution (multi-file project)
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);
const threshold = 3;
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);
const threshold = 5;
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);
  1. threshold ← 2, nums ← 1,2,3,4,5, kept ← 3,4,5, doubled ← 6,8,10

    1const threshold→ 2 = 2; //@threshold=3, 52const nums→ 1,2,3,4,5 = [1, 2, 3, 4, 5];3const kept→ 3,4,5 = nums1,2,3,4,5.filter((n) => n > threshold);4const doubled→ 6,8,10 = kept3,4,5.map((n) => n * 2);5const sum→ 24 = doubled6,8,10.reduce((acc, n) => acc + n, 0);67console.log("kept=" + kept3,4,5.join(","));8console.log("sum=" + sum24);
    outputkept=3,4,5
    sum=24
  1. threshold ← 3, nums ← 1,2,3,4,5, kept ← 4,5, doubled ← 8,10, sum ← 18

    1const threshold→ 3 = 3;2const nums→ 1,2,3,4,5 = [1, 2, 3, 4, 5];3const kept→ 4,5 = nums1,2,3,4,5.filter((n) => n > threshold);4const doubled→ 8,10 = kept4,5.map((n) => n * 2);5const sum→ 18 = doubled8,10.reduce((acc, n) => acc + n, 0);67console.log("kept=" + kept4,5.join(","));8console.log("sum=" + sum18);
    outputkept=4,5
    sum=18
  1. threshold ← 5, nums ← 1,2,3,4,5, kept ← (empty), doubled ← (empty)

    1const threshold→ 5 = 5;2const nums→ 1,2,3,4,5 = [1, 2, 3, 4, 5];3const kept→ (empty) = nums1,2,3,4,5.filter((n) => n > threshold);4const doubled→ (empty) = kept(empty).map((n) => n * 2);5const sum→ 0 = doubled(empty).reduce((acc, n) => acc + n, 0);67console.log("kept=" + kept(empty).join(","));8console.log("sum=" + sum0);
    outputkept=
    sum=0

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 |

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.