Arrays and Iteration
Array Methods
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
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|
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.