2

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?

BrokenBinary
  • 7,731
  • 3
  • 43
  • 54
Instasea
  • 151
  • 2
  • 7
  • 1
    `I don't want to use loop or map` Why not? Handy language tools are there to be used. An easy single-depth flatmap can be done via `const output = [].concat(...input.map(arr => arr));` – CertainPerformance Apr 18 '18 at 00:52
  • 1
    You can also find what you want at here. https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays-in-javascript – Tanaike Apr 18 '18 at 00:55
  • What about using `list[0]`? – Hassan Imam Apr 18 '18 at 03:43

2 Answers2

9

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))
CRice
  • 29,968
  • 4
  • 57
  • 70
7

Array.prototype.flat() The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

const arr = [ ['zone_1', 'zone_2'], ['zone_3'] ];
console.log(arr.flat());