Node.js中如何将二维数组转为一维数组?能否不使用循环或map?
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

