Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 2D Array Into 1D Array

I have this 2 dimensional array:

var list = [
    ['zone_1', 'zone_2'],
    ['zone_3']
]

I want to merge all elements in the sub-arrays into a single array:

var list = [
    'zone_1',
    'zone_2',
    'zone_3'
]

How can I do that in node.js? It is possible to do it without using a loop or map?

like image 860
Instasea Avatar asked May 05 '26 20:05

Instasea


1 Answers

The array .concat method is variadic, and you can use the spread operator to pass each sub-array to it as a separate argument. This makes flattening an array turn into a nice one-liner:

const arr = [ ['zone_1', 'zone_2'], ['zone_3'] ];
console.log([].concat(...arr))
like image 197
CRice Avatar answered May 07 '26 17:05

CRice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!