You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何将二维数组转为一维数组?能否不使用循环或map?

How to Flatten a 2D Array in Node.js Without Explicit Loops or map()

Great question! You can absolutely flatten your 2D array into a 1D array without writing explicit loops or using the map() method. Here are two clean, idiomatic approaches:

1. Use Array.prototype.flat() (Modern Node.js)

The easiest way is to use the built-in flat() method, which was added in Node.js 11.0.0. It’s designed specifically for flattening nested arrays, and since your array only has one level of nesting, you can call it without any arguments (default depth is 1):

var list = [ ['zone_1', 'zone_2'], ['zone_3'] ];
var flattenedList = list.flat();
console.log(flattenedList); // Output: ['zone_1', 'zone_2', 'zone_3']

2. Use concat() with the Spread Operator (Older Node.js Compatibility)

If you need to support Node.js versions before 11, you can combine Array.prototype.concat() with the spread operator (...). This works because concat() accepts multiple arguments, and spreading your array passes each sub-array as a separate argument to merge them all into one:

var list = [ ['zone_1', 'zone_2'], ['zone_3'] ];
var flattenedList = [].concat(...list);
console.log(flattenedList); // Output: ['zone_1', 'zone_2', 'zone_3']

Both of these methods avoid writing manual loops or using map()—the iteration happens under the hood in JavaScript’s native functions, so you don’t have to handle it yourself.

内容的提问来源于stack exchange,提问作者Instasea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:28:46