我有一个JavaScript数组,如:

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

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

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

当前回答

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
}

其他回答

有一种比使用上面的答案中列出的merge.contat.apply()方法快得多的方法来实现这一点,我的意思是速度快几个数量级。这假设您的环境可以访问ES5 Array方法。

var array2d = [
  ["foo", "bar"],
  ["baz", "biz"]
];
merged = array2d.reduce(function(prev, next) {
    return prev.concat(next);
});

这里是jsperf链接:http://jsperf.com/2-dimensional-array-merge

如果您的数组仅由整数或字符串组成,则可以使用这种肮脏的方法:

var arr = [345,2,[34],2,[524,[5456]],[5456]];
var flat = arr.toString().split(',');

Works,在FF、IE和Chrome中还没有测试其他浏览器。

我宁愿将整个数组按原样转换为字符串,但与其他答案不同,我会使用JSON.stringify而不使用toString()方法进行转换,这会产生不希望的结果。

有了JSON.stringify输出,剩下的就是删除所有括号,再次用开始和结束括号包装结果,并用JSON.parse提供结果,使字符串恢复“生命”。

可以处理无限嵌套数组,而无需任何速度成本。可以正确处理包含逗号的字符串的数组项。

var arr=[“abc”,[[[6],[“3,4”],“2”];var s=“[”+JSON.stringify(arr).replace(/\[|]/g,'')+“]”;var flatted=JSON.parse(s);console.log(展平)

仅适用于多维字符串/数字数组(非对象)

以下是使用堆栈的非递归展平深度的解决方案。

    function flatten(input) {
        const stack = [...input];
        const res = [];
        while (stack.length) {
            const next = stack.pop();
            if (Array.isArray(next)) {
                stack.push(...next);
            } else {
                res.push(next);
            }
        }
        return res.reverse();
    }
    const arrays = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
    flatten(arrays);

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


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。