javascript:尝试仅将数组展平一级

标签 javascript flatten

我正在尝试编写一个函数来展平数组。我有一部分功能在工作,另一半需要帮助。

flatten: function(anyArray, singleLevel) {
  if (singleLevel == true) {
      flatArray = Array.prototype.concat.apply([], anyArray);
      return flatArray;
  }
  flatArray = Array.prototype.concat.apply([], anyArray);
  if (flatArray.length != anyArray.length) {
      flatArray = someObject.array.flatten(flatArray);
  }
  return flatArray;
}

如果我输入

.flatten([[[1],[1,2,3,[4,5],4],[2,3]]], true);

我希望它只展平一层:

[[1],[1,2,3,[4,5],4],[2,3]]

最佳答案

现代 JavaScript 允许我们使用各种技术非常轻松地处理这个问题

使用Array.prototype.flat -

const arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
  
const flatArr =
  arr.flat(1) // 1 is default depth

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

使用Array.prototype.flatMap -

const arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
  
const flatArr =
  arr.flatMap(x => x)

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

使用 Array.prototype.concat 的扩展参数

const arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
  
const flatArr =
  [].concat(...arr)
  
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]


旧版本的 JavaScript(ECMAScript 5 及更低版本)可以使用 Function.prototype.apply 等技术 -

var arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
  
var flatArr =
  Array.prototype.concat.apply([], arr)
  
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

使用Array.prototype.reduce -

var arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

var flatArr =
  arr.reduce((r, a) => r.concat(a), [])

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

使用原始的 for 循环 -

var arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

var flatArr =
  []
  
for (var i = 0; i < arr.length; i = i + 1)
  flatArr = flatArr.concat(arr[i])

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

关于javascript:尝试仅将数组展平一级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15099123/

相关文章:

javascript - 有什么方法可以将单选按钮列表动态更改为选择下拉列表吗?

javascript - jquery collection/domRef 上的 Jquery 委托(delegate),但选择器字符串

javascript - Firebase SDK (Web) 创建基于密码的帐户

javascript - 用于递归展平结果的 JS 数组串联

python - 如何在 python 中将一个列表的异构列表展平为一个列表?

if-statement - 将数据从多列转换为行并保留 "labels"

javascript - WordPress 插件如何处理表单提交

javascript - Android相机权限请求不触发请求弹窗

Python:展平内部列表时保留外部列表

python - 将 [{str :int}, {str :int}, ... ] 的字典列表转换为 {str:int} 的单个字典