我有一个JavaScript数组,如:

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

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

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

当前回答

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链接

其他回答

更新:事实证明,这种解决方案不适用于大型阵列。如果您正在寻找更好、更快的解决方案,请查看此答案。


function flatten(arr) {
  return [].concat(...arr)
}

Is简单地展开arr并将其作为参数传递给concat(),concat将所有数组合并为一个数组。它相当于[].contat.apply([],arr)。

您也可以尝试此方法进行深压平:

function deepFlatten(arr) {
  return flatten(           // return shalowly flattened array
    arr.map(x=>             // with each x in array
      Array.isArray(x)      // is x an array?
        ? deepFlatten(x)    // if yes, return deeply flattened x
        : x                 // if no, return just x
    )
  )
}

请参阅JSBin上的演示。

本回答中使用的ECMAScript 6元素的引用:

Spread运算符箭头功能


附带说明:并非所有浏览器都支持find()和arrow函数等方法,但这并不意味着您现在不能使用这些功能。只需使用Babel-它将ES6代码转换为ES5。

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
}

有一个令人困惑的隐藏方法,它在不改变原始数组的情况下构造一个新数组:

var oldArray=[[1],[2,3],[4];var newArray=Array.prototype.contat.apply([],oldArray);console.log(newArray);//[ 1, 2, 3, 4 ]

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

最好使用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文档