Eugen Konkov
Eugen Konkov

Reputation: 25133

How to flattening array at javascript?

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

Answers (2)

zer00ne
zer00ne

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:

  • One-to-one: return [ value ]
  • One-to-none: return [ ]
  • One-to-many: return [ value, value -5, arbritaryValue ]

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

CertainPerformance
CertainPerformance

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

Related Questions