我有一个JavaScript数组,如:

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

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

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

当前回答

可以将Array.flat()与Infinity一起用于任何深度的嵌套数组。

var arr=[[1,2,3,4],[1,2,[1,2,3]],[1,2,4,5,[1,3,4,[12,3,4,[12,3,4]]],[[1,2,3-4],[1,3,[1,2],[1,2,3,5],[1,3,4,[1,2,3,4]]];let flatten=arr.flat(无限)console.log(展平)

在此处检查浏览器兼容性

其他回答

制作平面阵列的方法

使用Es6 flat()使用Es6 reduce()使用递归使用字符串操作

[1,[2,[3,[4,[5,[6,7],8],9],10]]] - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

//使用Es6 flat()设arr=[1,[2,[3,[4,[5,[6,7],8],9],10]]]console.log(arr.flat(无限))//使用Es6 reduce()let flatIt=(array)=>array.reduce((x,y)=>x.concat(Array.isArray(y)?flatIt(y):y),[])console.log(flatIt(arr))//使用递归函数myFlat(数组){let flat=[].contat(…数组);返回flat.some(Array.isArray)?myFlat(平面):平面;}console.log(myFlat(arr));//使用字符串操作let strArr=arr.toString().split(',');for(设i=0;i<strArr.length;i++)strArr[i]=parseInt(strArr[i]);console.log(strArr)

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
}

ES6的纯粹魔力

const flat = A => A.reduce((A, a) => Array.isArray(a) ? [...A, ...flat(a)] : [...A, a], []);
const arr = [1, 2, [3, 4]];

arr.reduce((acc, val) => acc.concat(val), []);

使用此方法展开两个阵列

arr1.concat(...arr2);