我有一个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);

其他回答

如果你使用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)

你可以使用Ramda JS flatten

var arr=[[1,2],[3],[4,5]];var flattedArray=R.flatten(arr);console.log(flattedArray)<script src=“https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js“></script>

由于ES2019引入了flat和flatMap,因此任何阵列都可以这样做:

const myArr = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
const myArrFlat= myArr.flat(Infinity);
console.log(myArrFlat); // ["$6", "$12", "$25", ...]

裁判。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

另一个功能风格的ECMAScript 6解决方案:

声明函数:

const flatten = arr => arr.reduce(
  (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
);

并使用它:

flatten( [1, [2,3], [4,[5,[6]]]] ) // -> [1,2,3,4,5,6]

常量flatten=arr=>arr.reduce((a,b)=>a.oncat(Array.isArray(b)?压扁(b):b),[]);console.log(展平([1,[2,3],[4],[5],[6],[7,8,9],10],11],[12],13])

还可以考虑在最新版本的现代浏览器中提供的本机函数Array.prototype.flat()(针对ES6的建议)。感谢@(КонстантинВа)和@(Mark Amery)在评论中提到了这一点。

flat函数有一个参数,指定数组嵌套的预期深度,默认值为1。

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

[1, 2, [3, 4, [5, 6]]].flat();          // -> [1, 2, 3, 4, [5, 6]]

[1, 2, [3, 4, [5, 6]]].flat(2);         // -> [1, 2, 3, 4, 5, 6]

[1, 2, [3, 4, [5, 6]]].flat(Infinity);  // -> [1, 2, 3, 4, 5, 6]

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

下面是现代浏览器的另一个深层次扁平化:

function flatten(xs) {
  xs = Array.prototype.concat.apply([], xs);
  return xs.some(Array.isArray) ? flatten(xs) : xs;
};