Reputation: 25133
I have code [ 1, 2, 3, fn(), 7, 8 ]
The fn
does next:
fn(){ return [ 5, 6 ] }
Which operator to apply to fn()
call to get:
[ 1, 2, 3, 5, 6, 7, 8 ]
instead of:
[ 1, 2, 3, [ 5, 6 ], 7, 8 ]
Of course It is possible to do:
[ 1, 2, 3, fn(), 7, 8 ].flat()
But at this case other elements will be flattened too. I need flattening only for fn()
Upvotes: 1
Views: 64
Reputation: 43880
flatMap()
returns values of the callback function of each element of the input array as an array which is then returned flattened. For example, the callback can be made to return the following:
In the demo if the value is an array -- it will be returned as is -- otherwise it will be returned within an array. Essentially, all values will be returned from callback as an array which in turn gets flattened.
const fn = () => [5, 6];
let array = [1, 2, 3, 4, fn(), 7, 8];
const result = array.flatMap(node => Array.isArray(node) ? node : [node]);
console.log(result);
Upvotes: 0
Reputation: 370729
When calling fn
, spread it into the array you're creating:
const fn = () => [ 5, 6 ];
const arr = [ 1, 2, 3, ...fn(), 7, 8, [9, 10]]
console.log(arr);
Upvotes: 4