我有一个JavaScript数组,如:

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

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

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

当前回答

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

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

其他回答

您可以使用Undercore:

var x = [[1], [2], [3, 4]];

_.flatten(x); // => [1, 2, 3, 4]

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

最好使用javascript reduce函数。

var arrays = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]];

arrays = arrays.reduce(function(a, b){
     return a.concat(b);
}, []);

或者,使用ES2015:

arrays = arrays.reduce((a, b) => a.concat(b), []);

js小提琴

Mozilla文档

我有一个简单的解决方案,不用在特殊的js函数中使用。(如减少等)

const input = [[0, 1], [2, 3], [4, 5]]
let flattened=[];

for (let i=0; i<input.length; ++i) {
    let current = input[i];
    for (let j=0; j<current.length; ++j)
        flattened.push(current[j]);
}

我写的简单的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 ]