O'Reilly logo

Mastering JavaScript Functional Programming by Federico Kereki

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required