我有一个JavaScript数组,如:

[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]

如何将单独的内部数组合并为一个,例如:

["$6", "$12", "$25", ...]

当前回答

要在一行中展平二维阵列,请执行以下操作:

[[1, 2], [3, 4, 5]].reduce(Function.prototype.apply.bind(Array.prototype.concat))
// => [ 1, 2, 3, 4, 5 ]

其他回答


ES2019年

ES2019引入了Array.protocol.flat()方法,您可以使用它来展平阵列。它与大多数环境兼容,尽管它仅在Node.js版本11开始提供,而在Internet Explorer中根本不提供。

常量数组=[["$6"],["$12"],["$25"],["$25"],["$18"],["$22"],["$10"]];const merge3=arrays.flat(1)//指定嵌套数组结构应展平的深度级别。默认值为1。console.log(合并3);


较旧的浏览器

对于较旧的浏览器,可以使用Array.prototype.cocat合并数组:

var数组=[["$6"],["$12"],["$25"],["$25"],["$18"],["$22"],["$10"]];var merged=[].contat.apply([],数组);console.log(合并);

使用concat的apply方法将只将第二个参数作为数组,因此最后一行与此相同:

var merged = [].concat(["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]);

由于ES2019引入了flat和flatMap,因此任何阵列都可以这样做:

const myArr = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
const myArrFlat= myArr.flat(Infinity);
console.log(myArrFlat); // ["$6", "$12", "$25", ...]

裁判。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

使用那里的代码。

我会写:

myArray.enumerable().selectMany(function(x) { return x; }).array()

更新:事实证明,这种解决方案不适用于大型阵列。如果您正在寻找更好、更快的解决方案,请查看此答案。


function flatten(arr) {
  return [].concat(...arr)
}

Is简单地展开arr并将其作为参数传递给concat(),concat将所有数组合并为一个数组。它相当于[].contat.apply([],arr)。

您也可以尝试此方法进行深压平:

function deepFlatten(arr) {
  return flatten(           // return shalowly flattened array
    arr.map(x=>             // with each x in array
      Array.isArray(x)      // is x an array?
        ? deepFlatten(x)    // if yes, return deeply flattened x
        : x                 // if no, return just x
    )
  )
}

请参阅JSBin上的演示。

本回答中使用的ECMAScript 6元素的引用:

Spread运算符箭头功能


附带说明:并非所有浏览器都支持find()和arrow函数等方法,但这并不意味着您现在不能使用这些功能。只需使用Babel-它将ES6代码转换为ES5。

以下代码将压平深度嵌套的数组:

/**
 * [Function to flatten deeply nested array]
 * @param  {[type]} arr          [The array to be flattened]
 * @param  {[type]} flattenedArr [The flattened array]
 * @return {[type]}              [The flattened array]
 */
function flattenDeepArray(arr, flattenedArr) {
  let length = arr.length;

  for(let i = 0; i < length; i++) {
    if(Array.isArray(arr[i])) {
      flattenDeepArray(arr[i], flattenedArr);
    } else {
      flattenedArr.push(arr[i]);
    }
  }

  return flattenedArr;
}

let arr = [1, 2, [3, 4, 5], [6, 7]];

console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4, 5 ], [ 6, 7 ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7 ]

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

console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4 ], [ 5, 6, [ 7, 8, [Object] ] ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]