最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert 2D Array Into 1D Array - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Apr 18, 2018 at 3:41 BrokenBinary 7,8793 gold badges45 silver badges54 bronze badges asked Apr 18, 2018 at 0:48 InstaseaInstasea 1512 silver badges8 bronze badges 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)); – CertainPerformance Commented Apr 18, 2018 at 0:52
  • 1 You can also find what you want at here. stackoverflow./questions/10865025/… – Tanaike Commented Apr 18, 2018 at 0:55
  • What about using list[0]? – Hassan Imam Commented Apr 18, 2018 at 3:43
Add a ment  | 

2 Answers 2

Reset to default 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))

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());
发布评论

评论列表(0)

  1. 暂无评论