January 2020
Intermediate to advanced
470 pages
11h 13m
English
We have already seen how reduce() could be used to emulate map(). Let's now see how to work out equivalents for flat() and flatMap() to get more practice. We'll also throw in a recursive version, a topic we'll come back to in Chapter 9, Designing Functions – Recursion. As was mentioned earlier, we are not aiming for the fastest or smallest or any particular version of the code; rather, we want to focus on using the concepts we've been looking at in this book.
Totally flattening an array can be done with a recursive call. We use reduce() to process the array element by element, and if an element happens to be an array, we recursively flatten it:
const flatAll = arr => arr.reduce((f, v) => f.concat(Array.isArray(v) ...
Read now
Unlock full access