Please support this book: buy it or donate

13. Array.prototype.{flat,flatMap}



13.1. Overview

The ES2019 feature Array.prototype.{flat,flatMap} (by Michael Ficarra, Brian Terlson, Mathias Bynens) adds two new methods to Arrays (to Array<T>.prototype): .flat() and .flatMap().

13.1.1. .flat()

The type signature of Array<T>.prototype.flat() is:

  1. .flat(depth = 1): any[]

.flat() “flattens” an Array: It creates a copy of the Array where values in nested Arrays all appear at the top level. The parameter depth controls how deeply .flat() looks for non-Array values. For example:

  1. > [ 1,2, [3,4], [[5,6]] ].flat(0) // no change
  2. [ 1, 2, [ 3, 4 ], [ [ 5, 6 ] ] ]
  3. > [ 1,2, [3,4], [[5,6]] ].flat(1)
  4. [ 1, 2, 3, 4, [ 5, 6 ] ]
  5. > [ 1,2, [3,4], [[5,6]] ].flat(2)
  6. [ 1, 2, 3, 4, 5, 6 ]

13.1.2. .flatMap()

The type signature of Array<T>.prototype.flatMap() is:

  1. .flatMap<U>(
  2. callback: (value: T, index: number, array: T[]) => U|Array<U>,
  3. thisValue?: any
  4. ): U[]

.flatMap() is the same as first calling .map() and then flattening the result. That is, the following two expressions are equivalent:

  1. arr.flatMap(func)
  2. arr.map(func).flat(1)

For example:

  1. > ['a', 'b', 'c'].flatMap(x => x)
  2. [ 'a', 'b', 'c' ]
  3. > ['a', 'b', 'c'].flatMap(x => [x])
  4. [ 'a', 'b', 'c' ]
  5. > ['a', 'b', 'c'].flatMap(x => [[x]])
  6. [ [ 'a' ], [ 'b' ], [ 'c' ] ]
  7. > ['a', 'b', 'c'].flatMap((x, i) => new Array(i+1).fill(x))
  8. [ 'a', 'b', 'b', 'c', 'c', 'c' ]

13.2. More information on .flatMap()

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. That is, f returns a single value.
  • With .flatMap(), each input Array element is translated to zero or more output elements. That is, f returns an Array of values (it can also return non-Array values, but that is less common). This is an implementation of .flatMap() (a simplified version of JavaScript’s implementation that does not conform to the specification):
  1. function flatMap(arr, mapFunc) {
  2. const result = [];
  3. for (const [index, elem] of arr.entries()) {
  4. const x = mapFunc(elem, index, arr);
  5. // We allow mapFunc() to return non-Arrays
  6. if (Array.isArray(x)) {
  7. result.push(...x);
  8. } else {
  9. result.push(x);
  10. }
  11. }
  12. return result;
  13. }

.flatMap() is simpler if mapFunc() is only allowed to return Arrays, but JavaScript doesn’t impose this restriction, because non-Array values are occasionally useful (see the section on .flat() for an example).

What is .flatMap() good for? Let’s look at use cases!

13.3. Use case: filtering and mapping at the same time

The result of the Array method .map() always has the same length as the Array it is invoked on. That is, its callback can’t skip Array elements it isn’t interested in.

The ability of .flatMap() to do so is useful in the next example: processArray() returns an Array where each element is either a wrapped value or a wrapped error.

  1. function processArray(arr, process) {
  2. return arr.map(x => {
  3. try {
  4. return { value: process(x) };
  5. } catch (e) {
  6. return { error: e };
  7. }
  8. });
  9. }

The following code shows processArray() in action:

  1. let err;
  2. function myFunc(value) {
  3. if (value < 0) {
  4. throw (err = new Error('Illegal value: '+value));
  5. }
  6. return value;
  7. }
  8. const results = processArray([1, -5, 6], myFunc);
  9. assert.deepEqual(results, [
  10. { value: 1 },
  11. { error: err },
  12. { value: 6 },
  13. ]);

.flatMap() enables us to extract just the values or just the errors from results:

  1. const values = results.flatMap(
  2. result => result.value ? [result.value] : []);
  3. assert.deepEqual(values, [1, 6]);
  4. const errors = results.flatMap(
  5. result => result.error ? [result.error] : []);
  6. assert.deepEqual(errors, [err]);

13.4. Use case: mapping to multiple values

The Array method .map() maps each input Array element to one output element. But what 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']}
  2. 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 separated by commas:
  1. class TagList extends React.Component {
  2. render() {
  3. const {tags, handleClick} = this.props;
  4. return tags.flatMap(
  5. (tag, index) => {
  6. const link = <a key={index} href=""
  7. onClick={e => handleClick(tag, e)}>
  8. {tag}
  9. </a>;
  10. if (index === 0) {
  11. return [link];
  12. } else {
  13. return [', ', link];
  14. }
  15. }
  16. );
  17. }
  18. }

Due to .flatMap(), TagList is rendered as a single flat Array. The first tag contributes one element to this Array (a link); each of the remaining tags contributes two elements (comma and link).

13.5. Other versions of .flatMap()

13.5.1. Arbitrary iterables

.flatMap() can be generalized to work with arbitrary iterables:

  1. function* flatMapIter(iterable, mapFunc) {
  2. let index = 0;
  3. for (const x of iterable) {
  4. yield* mapFunc(x, index);
  5. index++;
  6. }
  7. }

Due to Arrays being iterables, you can process them via flatMapIter():

  1. function fillArray(x) {
  2. return new Array(x).fill(x);
  3. }
  4. const iterable = flatMapIter([1,2,3], fillArray);
  5. assert.deepEqual(
  6. [...iterable], // convert to Array, to check contents
  7. [1, 2, 2, 3, 3, 3]);

One benefit of flatMapIter() is that it works incrementally: as soon as the first input value is available, output is produced. In contrast, the Array-based .flatMap() needs all of its input to produce its output.

That can be demonstrated via the infinite iterable created by the generator function naturalNumbers():

  1. function* naturalNumbers() {
  2. for (let n=0;; n++) {
  3. yield n;
  4. }
  5. }
  6. const infiniteInput = naturalNumbers();
  7. const infiniteOutput = flatMapIter(infiniteInput, fillArray);
  8. const [a,b,c,d,e] = infiniteOutput; // (A)
  9. assert.deepEqual([a,b,c,d,e], [1, 2, 2, 3, 3]);

In line A, we extract the first 5 values of infiniteOutput via destructuring.

13.5.2. Implementing .flatMap() via .reduce()

We can use the Array method .reduce() to implement a simple version of .flatMap():

  1. function flatMap(arr, mapFunc) {
  2. return arr.reduce(
  3. (prev, x) => prev.concat(mapFunc(x)),
  4. []
  5. );
  6. }

It depends on your taste, if you prefer the original, more efficient imperative version or this more concise functional version.

13.6. More information on .flat()

This is an implementation of .flat() (a simplified version of JavaScript’s implementation, that does not conform to the ECMAScript specification):

  1. function flat(arr, depth) {
  2. return flatInto(arr, depth, []);
  3. }
  4. function flatInto(value, depth, target) {
  5. if (!Array.isArray(value)) {
  6. target.push(value);
  7. } else {
  8. for (const x of value) {
  9. if (depth >= 1) {
  10. flatInto(x, depth-1, target);
  11. } else {
  12. target.push(x);
  13. }
  14. }
  15. }
  16. return target;
  17. }

.flat() with a depth of 1 can also be implemented as follows:

  1. const flat = (arr) => [].concat(...arr)

.flat(1) is the same as using .flatMap() with the identity function (x => x). That is, the following two expressions are equivalent:

  1. arr.flatMap(x => x)
  2. arr.flat(1)

The next subsections cover use cases for .flat().

13.6.1. Use case: conditionally inserting values into an Array

The following code only inserts 'a' if cond is true:

  1. const cond = false;
  2. const arr = [
  3. (cond ? 'a' : []),
  4. 'b',
  5. ].flat();
  6. assert.deepEqual(arr, ['b']);

Caveat: If you replace either 'a' or 'b' with an Array, then you have to wrap it in another Array.

13.6.2. Use case: filtering out failures

In the following example, downloadFiles() only returns the texts that could be downloaded.

  1. async function downloadFiles(urls) {
  2. const downloadAttempts = await Promises.all( // (A)
  3. urls.map(url => downloadFile(url)));
  4. return downloadAttempts.flat(); // (B)
  5. }
  6. async function downloadFile(url) {
  7. try {
  8. const response = await fetch(url);
  9. const text = await response.text();
  10. return [text]; // (C)
  11. } catch (err) {
  12. return []; // (D)
  13. }
  14. }

downloadFiles() first maps each URL to a Promise resolving to either:

  • An Array with the successfully downloaded text (line C)
  • An empty Array (line D) Promises.all() (line A) converts the Array of Promises into a Promise that resolves to a nested Array. await (line A) unwraps that Promise and .flat() un-nests the Array (line B).

Note that we couldn’t have used .flatMap() here, because of the barrier imposed by the Promises returned by downloadFile(): when it returns a value, it doesn’t know yet if it will be a text or an empty Array.

13.7. FAQ

13.7.1. Do .flat() and .flatMap() also flatten iterable elements?

No, only Arrays are flattened:

  1. const set = new Set([3,4]);
  2. assert.deepEqual(
  3. [[1,2], set].flat(),
  4. [1, 2, set]);

13.8. Further reading