Borislav Hadzhiev
Wed Oct 20 2021·2 min read
Photo by Adetunji Paul
The "flatMap is not a function" error occurs for multiple reasons:
flatMap
method in a browser that doesn't support it.flatMap
method on a value that is not an array.Here is an example of how the error occurs.
const arr = {}; // ⛔️ TypeError: arr.flatMap is not a function const result = arr.flatMap(str => str.split(' '));
We called the Array.flatMap() method on an object and got the error back.
To solve the "flatMap is not a function" error, make sure to only call the
flatMap
method on arrays and in browsers that support it. The flatMap
method
returns a new array where each element is the result of the callback function
flattened to a depth of 1.
const arr = ['one two', 'three four']; const result = arr.flatMap(str => str.split(' ')); // 👇️ ['one', 'two', 'three', 'four'] console.log(result);
flatMap
method is not supported in Internet Explorer. If you have to support the browser, you can use the combination of reduce
and concat
.// ✅ Supported in Internet Explorer const arr = ['one two', 'three four']; const result = arr.reduce((acc, curr) => acc.concat(curr.split(' ')), []); // 👇️ ['one', 'two', 'three', 'four'] console.log(result);
flatMap
directly.You can conditionally check if the value is an array by using the Array.isArray method.
const arr = null; const result = Array.isArray(arr) ? arr.flatMap(str => str.split(' ')) : []; console.log(result); // 👉️ []
We used a ternary operator, which is very similar to an if/else
statement.
If the value is an array, we return the result of calling the flatMap
method
on it, otherwise we return an empty array. This way, you won't get an error,
even if the value is not an array.
flatMap
method on it.If you have an array-like object which you're trying to convert to an array
before calling the flatMap
method, use the Array.from
method.
const set = new Set(['one two', 'three four']); const result = Array.from(set).flatMap(str => str.split(' ')); console.log(result); // 👉️ ['one', 'two', 'three', 'four']
Before calling the flatMap
method, we convert the value to an array.
You could also use the spread syntax (...) to achieve the same result.
const set = new Set(['one two', 'three four']); const result = [...set].flatMap(str => str.split(' ')); console.log(result); // 👉️ ['one', 'two', 'three', 'four']
If the error persists, console.log
the value you're calling the flatMap
method on and make sure it's a valid array.