我有一个JavaScript数组,如:

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

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

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

当前回答

const arr = [1, 2, [3, 4]];

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

其他回答

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

/**
 * [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 ]

您也可以尝试新的Array.flat()方法。其工作方式如下:

let arr=[[“$6”],[“$12”],【“$25”】,[“$25“],【”$18“】,【”$22“】,[”$10“]].flat()控制台日志(arr);

flat()方法创建一个新数组,所有子数组元素递归地连接到其中,直到1层深度(即数组内部的数组)

如果您还想展平三维或更高维度的数组,只需多次调用flat方法。例如(三维):

设arr=[1,2,[3,4,[5,6]]].flat().flat;控制台日志(arr);

小心!

Array.flat()方法相对较新。像ie这样的旧浏览器可能没有实现该方法。如果你想让你的代码在所有浏览器上运行,你可能需要将你的JS转换成一个旧版本。检查MDN web文档的当前浏览器兼容性。

您可以继续使用Array.flat()方法来实现这一点,即使数组嵌套得更多。

[1,2,3,[2]].flat() 

相当于

[1,2,3,[2]].flat(1)

所以当你的筑巢增加时,你可以继续增加数量。

eg:

[1,[2,[3,[4]]]].flat(3) // [1, 2, 3, 4]

如果您不确定嵌套的级别,可以只传递Infinity作为参数

[1,2,3,[2,[3,[3,[34],43],[34]]]].flat(Infinity) //[1, 2, 3, 2, 3, 3, 34, 43, 34]

要展平单个元素数组的数组,不需要导入库,简单的循环是最简单和最有效的解决方案:

for (var i = 0; i < a.length; i++) {
  a[i] = a[i][0];
}

对反对选民:请阅读问题,不要因为它不适合你的不同问题而反对投票。对于所问的问题,此解决方案是最快和最简单的。

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
}