我有一个JavaScript数组,如:

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

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

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

当前回答

我只使用ES6回答这个问题,假设深度阵列是:

const deepArray = ['1',[['a'],['b']],[2],[[[['4',[3,'c']]]],[5]]];

如果您知道或猜测阵列的深度不超过7这样的数字,请使用以下代码:

const flatArray = deepArray.flat(7);

但如果你不知道深度数组的深度,或者你的JavaScript引擎不支持像react原生JavaScriptCore那样的flat,请使用下面的JavaScript reduce函数:

 const deepFlatten = arr =>
         arr.reduce(
           (acc, val) =>
             Array.isArray(val) 
               ? acc.concat(deepFlatten(val)) 
               : acc.concat(val),
             []
         );

这两种方法都返回以下结果:

["1", "a", "b", 2, "4", 3, "c", 5]

其他回答

如果你使用lodash,你可以使用它的flatten方法:https://lodash.com/docs/4.17.14#flatten

lodash的优点是它还具有使数组变平的方法:

i) 递归地:https://lodash.com/docs/4.17.14#flattenDeep

ii)多达n层嵌套:https://lodash.com/docs/4.17.14#flattenDepth

例如

const _ = require("lodash");
const pancake =  _.flatten(array)
let arr = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]];
arr = arr.reduce((a, b) => a.concat(b)); // flattened

我写的简单的flatten util

const flatten = (arr, result = []) => {
    if (!Array.isArray(arr)){
        return [...result, arr];
    }
     arr.forEach((a) => {
         result = flatten(a, result)
    })

    return result
}

console.log(flatten([1,[2,3], [4,[5,6,[7,8]]]])) // [ 1, 2, 3, 4, 5, 6, 7, 8 ]
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
}

您也可以尝试新的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文档的当前浏览器兼容性。