如何将数组内的数组合并为一个数组?

时间:2017-02-25 18:01:41

标签: javascript arrays

我有这个数组:

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

如何在JavaScript中将其转换为此数组?

[5,27,39,1001]

1 个答案:

答案 0 :(得分:0)

实现结果的几种方法



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);
  })
)