我有一个JavaScript数组,如:

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

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

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

当前回答

请注意:当使用Function.prototype.apply([].contat.apply([],arrays))或扩展运算符([].cantat(…arrays),以展平数组时,这两者都会导致大型数组的堆栈溢出,因为函数的每个参数都存储在堆栈上。

这里是一个以功能风格实现的堆栈安全实现,它将最重要的需求相互权衡:

可重用性可读性简洁表演

//小型、可重复使用的辅助功能:常量foldl=f=>acc=>xs=>xs.reduce(uncurry(f),acc);//aka减少常量未修正=f=>(a,b)=>f(a)(b);常量concat=xs=>y=>xs.contat(y);//使数组变平的实际函数-一个不言自明的单行:常量flatten=xs=>foldl(concat)([])(xs);//任意数组大小(直到堆爆炸:D)常量xs=[[1,2,3],[4,5,6],[7,8,9]];console.log(flatten(xs));//推导深度嵌套数组的递归解决方案现在很简单//更小型、可重复使用的辅助功能:const-map=f=>xs=>xs.map(apply(f));常量应用=f=>a=>f(a);const-isArray=Array.isArray;//导出的递归函数:const flattenr=xs=>flatten(map(x=>isArray(x)?flatnr(x):x)(xs));常量ys=[1,[2,[3,[4,[5],6,],7],8],9];控制台日志(flatnr(ys));

一旦您习惯了小箭头函数的通用形式、函数组合和更高阶的函数,这段代码读起来就像散文一样。然后,编程只包括将总是按预期工作的小构件组合在一起,因为它们不包含任何副作用。

其他回答

Haskell式方法

函数flatArray([x,…xs]){返回x?[…Array.isArray(x)?flatArray(x):[x]。。。flatArray(xs)]:[];}var na=[[1,2],[3,[4,5]],[6,7,[[[8],9],10];fa=平面阵列(na);console.log(fa);

您可以使用Undercore:

var x = [[1], [2], [3, 4]];

_.flatten(x); // => [1, 2, 3, 4]

如何使用JavaScript 1.8的reduce(callback[,initialValue])方法

list.reduce((p,n) => p.concat(n),[]);

能胜任这项工作。

适用于所有数据类型的递归版本

 /*jshint esversion: 6 */

// nested array for testing
let nestedArray = ["firstlevel", 32, "alsofirst", ["secondlevel", 456,"thirdlevel", ["theinnerinner", 345, {firstName: "Donald", lastName: "Duck"}, "lastinner"]]];

// wrapper function to protect inner variable tempArray from global scope;
function flattenArray(arr) {

  let tempArray = [];

  function flatten(arr) {
    arr.forEach(function(element) {
      Array.isArray(element) ? flatten(element) : tempArray.push(element);     // ternary check that calls flatten() again if element is an array, hereby making flatten() recursive.
    });
  }

  // calling the inner flatten function, and then returning the temporary array
  flatten(arr);
  return tempArray;
}

// example usage:
let flatArray = flattenArray(nestedArray);

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


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。