Both map()
and flatMap()
take a function f
as a parameter that controls how an input Array is translated to an output Array:
With
map()
, each input Array element is translated to exactly one output element, aka,f
returns a single valueWith
flatMap()
, each input Array element is translated to zero or more output elements, aka,f
returns an Array of values.
An smiple implementation of flatMap
:
1 | function flatMap (arr, mapFunc) { |
flatMap
is simpler if mapFunc
is only allowed to return Arrays, but we don’t impose this restriction here, because non-Array values are occasionally useful.
Filtering and mapping at the same time
1 | function processArray (arr, processFunc) { |
Mapping to multiple values
The Array method map()
maps each input Array element to one output. But if we want to map it to multiple output elements?
That becomes necessary in the following example: The React component TagList
is invoked with two attributes
1 | <TagList tags={['foo', 'bar', 'baz']} handleClick={x => console.log(x)} /> |
The attributes are:
An Array of tags, each tag being a string
A callback for handling clicks on tags
TagList
is rendered as a series of links seperated by commas:
1 | class TagList extends React.Component { |
Here each tag (except the first) provide two elements in the rendered Array
Arbitrary Iterables
flatMap
can be generalized to work with arbitrary iterables
1 | function* flatMapIter(iterable, mapFunc) { |
flatMapIter
function works with Arrays:
1 | function fillArray () { |
Implementing flatMap
via reduce
You can use the Array method reduce
to implement a simple version of flatMap
1 | function flatMap (arr, mapFunc) { |
Related to flatMap
: flatten
flatten
is an operation that concatenates all the elements of an Array
1 | > flatten(['a', ['b', 'c'], ['d']]) |
It can be implemented as follows:
1 | const flatten = (arr) => [].concat(...arr) |
So the following expressions are equivalent
1 | flatten(arr.map(func)) |