Reputation: 1715
Passing Array.from as a callback to Array.flatMap causes an error: "TypeError: 0 is not a function"
const x = ["12"].flatMap(Array.from)
console.log(x)
Despite this Array.from is usable as a function normally:
const f = Array.from
console.log(f("12"))
I have found a way around this:
const x = ["12"].flatMap(e => Array.from(e))
console.log(x)
I would like someone to tell me:
Upvotes: 1
Views: 751
Reputation: 2822
Array.from
accepts up to 3 parameters, the second one being map function while .flatMap
will pass to it iteration index as the second parameter.
So, on the first iteration, Array.from
will recieve 0
as a second parameter, which, indeed, is not a function that Array.from
expects.
To demonstrate it more clearly, here is a snippet. This line:
["12"].flatMap(Array.from);
is functionally equivalent to:
Array.from("12", 0, ["12"]);
which is an incorrect signature for Array.from
.
Upvotes: 3
Reputation: 6769
It happends because the flatMap passes more than 1 argument to the callback. The second argument is the index of the element. Array.from function expects a replacer function in the second argument. So this shortened version passed an index in place of a function.
What you're doing is equivalent to calling:
Array.from("12", 0)
Instead of a proper replacer like:
console.log(Array.from("12", x => x + x));
Upvotes: 3