【问题标题】:How do I combine arrays inside arrays into a single array? [duplicate]如何将数组内的数组组合成一个数组? [复制]
【发布时间】:2017-07-16 12:36:27
【问题描述】:

我有这个数组:

[[5],[27],[39],[1001]]

如何在 JavaScript 中将其转换成这个数组?

[5,27,39,1001]

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 子数组可以包含多个元素吗?它们本身可以包含子子数组吗?

标签: javascript arrays


【解决方案1】:

实现结果的几种方法

var data = [
  [5],
  [27],
  [39],
  [1001]
];

// Use map method which iterate over the array and within the 
// callback return the new array element which is first element
// from the inner array, this won't work if inner array includes 
// more than one element
console.log(
  data.map(function(v) {
    return v[0];
  })
)

// by concatenating the inner arrays by providing the array of
// elements as argument using `apply` method
console.log(
  [].concat.apply([], data)
)

// or by using reduce method which concatenate array 
// elements within the callback
console.log(
  data.reduce(function(arr, e) {
    return arr.concat(e);
  })
)

【讨论】:

  • 不错的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-30
  • 2021-11-24
  • 2020-07-24
  • 1970-01-01
  • 2019-12-05
相关资源
最近更新 更多