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,9493 gold badges46 silver badges55 bronze badges
asked Apr 18, 2018 at 0:48
3
  • 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)); Commented Apr 18, 2018 at 0:52
  • 1
    You can also find what you want at here. stackoverflow.com/questions/10865025/… Commented Apr 18, 2018 at 0:55
  • What about using list[0]? Commented Apr 18, 2018 at 3:43

2 Answers 2

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))

answered Apr 18, 2018 at 0:52
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much CRice. It works now. It is the one that I wanted.
8

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());
answered Jan 6, 2020 at 17:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.