Array Iteration: map, filter, reduce
Ditch the classic for-loop. Learn how to process, filter, and summarize arrays using modern declarative functions.
Higher-Order Functions
Historically, developers used for loops to process arrays. Modern JavaScript uses 'higher-order functions' - functions that accept *other* functions as arguments - to iterate declaratively.
Instead of telling the computer *how* to loop, you simply tell it *what* to do with each item.
Map and Filter
map() runs your callback function on every item in the array and returns a brand new array of the exact same length containing the transformed results. It is perfect for converting data (e.g., turning an array of strings into an array of React components).
filter() runs your callback function as a test. If the callback returns true, the item is kept. If false, it is discarded. It returns a new array that is usually shorter than the original.
Reduce and Chaining
reduce() is the ultimate Swiss Army knife. It takes an array and 'reduces' it down to a single value, like a sum of numbers or a single combined object. It requires a callback and an initial starting value.
Because map and filter both return new arrays, you can **chain** them together! You can filter out bad data, map the good data, and reduce it to a final answer in one elegant, unbroken line of code.
The Assembly Line
Step through a chained operation to see how data flows from a map, into a filter, and finally into a reduce.
The Assembly Line
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
map()transforms data 1-to-1, returning a new array of the same length.filter()tests data, returning a new array containing only items that passed.reduce()boils an entire array down into a single value.- These methods are safe because they do not mutate the original array.
- Because
mapandfilterreturn arrays, they can be chained together sequentially.
Done with this concept?
Mark it complete to track your progress. No login needed.