我有一个JavaScript数组,如:

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

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

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

当前回答

这是递归方法。。。

function flatten(arr){
    let newArray = [];
    for(let i=0; i< arr.length; i++){
        if(Array.isArray(arr[i])){
          newArray =  newArray.concat(flatten(arr[i]))
        }else{
          newArray.push(arr[i])
        }
    }
  return newArray; 
}

console.log(flatten([1, 2, 3, [4, 5] ])); // [1, 2, 3, 4, 5]
console.log(flatten([[[[1], [[[2]]], [[[[[[[3]]]]]]]]]]))  // [1,2,3]
console.log(flatten([[1],[2],[3]])) // [1,2,3]

其他回答

我有一个简单的解决方案,不用在特殊的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]);
}

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

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

您可以继续使用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]

如果您的编码环境支持ES6(ES2015),那么您不需要编写任何递归函数或使用map、reduce等数组方法。

一个简单的排列运算符(…)将帮助您将一个数组展平为单个数组

eg:

  const data = [[1, 2, 3], [4, 5],[2]]
  let res = []
  data.forEach(curSet=>{
      res = [...res,...curSet]
  })
  console.log(res) //[1, 2, 3, 4, 5, 2]

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