I know you said you didn't want to define it yourself, but this implementation is a pretty trivial definition.
There's also this from the same github page:
Here is a bit of shorter way using es6 spread, similiar to renaudtertrais's - but using es6 and not adding to the prototype.
var flatMap = (a, cb) => [].concat(...a.map(cb))
const s = (v) => v.split(',')
const arr = ['cat,dog', 'fish,bird']
flatMap(arr, s)
Would either of these help?
It should be noted (thanks to @ftor) that this latter "solution" suffers from "Maximum call stack size exceeded" if called on a really large (e.g., 300k elements) array a.
Because programming isn't magic and every language doesn't have features/primitives that every other language has. What matters is JavaScript gives you the ability to define it on your own -
Lodash provides a flatmap function, which to me is practically equivalent to Javascript providing it natively. If you're not a Lodash user, then ES6's Array.reduce() method can give you the same result, but you have to map-then-flatten in discrete steps.
Below is an example of each method, mapping a list of integers and returning only the odds.
We now have a flatMap() in Javascript! And it is supported pretty well
The flatMap() method first maps each element using a mapping function,
then flattens the result into a new array. It is identical to a map()
followed by a flat() of depth 1
const dublicate = x => [x, x];
console.log([1, 2, 3].flatMap(dublicate))
Array.prototype.flatMap() has now arrived in JS. However, not all browser might support them check for the current browser compatibility the Mozilla web docs.
What the flatMap() method does is first maps each element using a callback function as argument, then flattens the result into a new array (the 2d array is now 1d since the elements are flattened out).
Here is also an example of how to use the function:
let arr = [[2], [4], [6], [8]]
let newArr = arr.flatMap(x => [x * 2]);
console.log(newArr);