Mapping and filtering

Mapping and filtering are quite similar, insofar both imply going through all the elements in an array and applying a callback to each to produce output. Let's work out first the mapping logic, which will have several points to solve, and then filtering will become almost trivially easy, requiring just small changes.

For mapping, according to the way we are using to develop recursive functions, we need a base case. Fortunately, that's easy: mapping an empty array just produces a new empty array. Mapping a non-empty array can be done by first applying the mapping function to the first element of the array, then recursively mapping the rest of the array, and finally producing a single array accumulating both results.

Get Mastering Javascript Functional Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.