我有一个JavaScript数组,如:

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

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

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

当前回答

只需使用扩展运算符,我们可以按以下方式展平。

var OriginalArray=[[5,1],[6],[2],[8]];var newArray=[];for(设i=0;i<OriginalArray.length;i++){newArray.push(…OriginalArray[i]);}console.log(newArray)

其他回答

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

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

这里的大多数答案都不适用于大型(例如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]]]);

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

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
}

更简单和直接的方法;可选择深压平;

const flatReduce = (arr, deep) => {
    return arr.reduce((acc, cur) => {
        return acc.concat(Array.isArray(cur) && deep ? flatReduce(cur, deep) : cur);
    }, []);
};

console.log(flatReduce([1, 2, [3], [4, [5]]], false)); // =>  1,2,3,4,[5]
console.log(flatReduce([1, 2, [3], [4, [5, [6, 7, 8]]]], true)); // => 1,2,3,4,5,6,7,8
let arr = [1, [2, 3, [4, 5, [6, 7], [8, 9, 10, 11, 12]]]];

function flattenList(nestedArr) {
  let newFlattenList = [];

  const handleFlat = (array) => {
    let count = 0;
    while (count < array.length) {
      let item = array[count];
      if (Array.isArray(item)) {
        handleFlat(item);
      } else {
        newFlattenList.push(item);
      }
      count++;
    }
  };
  handleFlat(nestedArr);
  return newFlattenList;
}`enter code here`

console.log(flattenList(arr));

CodeSandBox链接