我有一个JavaScript数组,如:

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

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

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

当前回答

使用那里的代码。

我会写:

myArray.enumerable().selectMany(function(x) { return x; }).array()

其他回答

以下代码将压平深度嵌套的数组:

/**
 * [Function to flatten deeply nested array]
 * @param  {[type]} arr          [The array to be flattened]
 * @param  {[type]} flattenedArr [The flattened array]
 * @return {[type]}              [The flattened array]
 */
function flattenDeepArray(arr, flattenedArr) {
  let length = arr.length;

  for(let i = 0; i < length; i++) {
    if(Array.isArray(arr[i])) {
      flattenDeepArray(arr[i], flattenedArr);
    } else {
      flattenedArr.push(arr[i]);
    }
  }

  return flattenedArr;
}

let arr = [1, 2, [3, 4, 5], [6, 7]];

console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4, 5 ], [ 6, 7 ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7 ]

arr = [1, 2, [3, 4], [5, 6, [7, 8, [9, 10]]]];

console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4 ], [ 5, 6, [ 7, 8, [Object] ] ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Haskell式方法

函数flatArray([x,…xs]){返回x?[…Array.isArray(x)?flatArray(x):[x]。。。flatArray(xs)]:[];}var na=[[1,2],[3,[4,5]],[6,7,[[[8],9],10];fa=平面阵列(na);console.log(fa);

这里的大多数答案都不适用于大型(例如200000个元素)阵列,即使这样,它们也很慢。

以下是最快的解决方案,它也适用于具有多层嵌套的阵列:

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

示例

巨大的阵列

flatten(Array(200000).fill([1]));

它可以很好地处理巨大的数组。在我的机器上,执行这段代码需要大约14毫秒。

嵌套数组

flatten(Array(2).fill(Array(2).fill(Array(2).fill([1]))));

它适用于嵌套数组。此代码生成[1,1,1,2,1,3,1,1]。

具有不同嵌套级别的数组

flatten([1, [1], [[1]]]);

它对像这样的扁平化阵列没有任何问题。

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

    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()与Infinity一起用于任何深度的嵌套数组。

var arr=[[1,2,3,4],[1,2,[1,2,3]],[1,2,4,5,[1,3,4,[12,3,4,[12,3,4]]],[[1,2,3-4],[1,3,[1,2],[1,2,3,5],[1,3,4,[1,2,3,4]]];let flatten=arr.flat(无限)console.log(展平)

在此处检查浏览器兼容性