Arrays and Iteration
Array Methods
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
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);
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
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
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
thresholdstarts as2.filterkeeps values greater than2:3,4, and5.mapdoubles those kept values into6,8, and10.reduceadds the doubled values.- The script prints
kept=3,4,5andsum=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.