我有一个JavaScript数组,如:

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

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

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

当前回答

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

其他回答

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

[[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"]);

请注意:当使用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));

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

ES6的纯粹魔力

const flat = A => A.reduce((A, a) => Array.isArray(a) ? [...A, ...flat(a)] : [...A, a], []);
const flatten = array => array.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []); 

根据请求,分解一行基本上就是这样。

function flatten(array) {
  // reduce traverses the array and we return the result
  return array.reduce(function(acc, b) {
     // if is an array we use recursion to perform the same operations over the array we found 
     // else we just concat the element to the accumulator
     return acc.concat( Array.isArray(b) ? flatten(b) : b);
  }, []); // we initialize the accumulator on an empty array to collect all the elements
}