我有一个JavaScript数组,如:

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

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

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

当前回答

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 flattenArray = () => {
                let result = [];
                return function flatten(arr) {
                    for (let i = 0; i < arr.length; i++) {
                        if (!Array.isArray(arr[i])) {
                            result.push(arr[i]);
                        } else {
                            flatten(arr[i])
                        }
                    }
                    return result;
                }
            }

测试结果:https://codepen.io/ashermike/pen/mKZrWK

Array.prototype.flatten = Array.prototype.flatten || function() {
    return [].reduce.call(this, function(flat, toFlatten) {
        return flat.concat(Array.isArray(toFlatten) ? toFlatten.flatten() : toFlatten);
    },[])
};

您可以使用array.prototype.reduce()和array.protocol.contat()展平数组

var data=[[“$6”],[“$12”],【“$25”】,[“$25“],【”$18”】,【”$22“】,【“$10”】,“$15”】、【”$3“】,[”$75“],[”$5“],“$100”]、【”$7“】、【“$3”】、“$75”],“$5”]]。reduce(函数(a,b){返回a.concat(b);}, []);console.log(数据);

相关文档:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

要展平单个元素数组的数组,不需要导入库,简单的循环是最简单和最有效的解决方案:

for (var i = 0; i < a.length; i++) {
  a[i] = a[i][0];
}

对反对选民:请阅读问题,不要因为它不适合你的不同问题而反对投票。对于所问的问题,此解决方案是最快和最简单的。

我最初想使用.reduce方法并递归调用一个函数来展平内部数组,但是当使用深度嵌套数组的深度嵌套数组时,这可能会导致堆栈溢出。使用concat也不是最好的方法,因为每次迭代都会创建数组的新浅层副本。我们可以做的是:

const flatten = arr => {
    for(let i = 0; i < arr.length;) {
        const val = arr[i];
        if(Array.isArray(val)) {
            arr.splice(i, 1, ...val);
        } else {
            i ++;
        }
    }
    return arr;
}

我们没有通过concat创建新数组,也没有递归调用任何函数。

http://jsbin.com/firiru/4/edit?js安慰