我有一个JavaScript数组,如:

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

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

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

当前回答

简单并处理多个嵌套级别:

// deeply nested array
const myArray = [1, 2, [3, 4, [5, 6, [[[7,8, [[[[[9, 10]]]]]]]]]]] ;

const flatten = (arr) => {
    for (let index = 0; index < arr.length; index++) {
        const elem = arr[index];

        if (Array.isArray(elem)) {
            arr.splice(index, 1, ...elem);
            index--;
        }
    }
};

flatten(myArray);
console.log(myArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

其他回答

我只是在寻找一个更快更简单的解决方案,为什么?因为我是一个面试问题,我很好奇,所以我做了这个:

function flattenArrayOfArrays(a, r){
    if(!r){ r = []}
    for(var i=0; i<a.length; i++){
        if(a[i].constructor == Array){
            flattenArrayOfArrays(a[i], r);
        }else{
            r.push(a[i]);
        }
    }
    return r;
}

var i = [[1,2,[3]],4,[2,3,4,[4,[5]]]], output;

// Start timing now
console.time("flatten");
output = new Array(JSON.stringify(i).replace(/[^\w\s,]/g,"")); 
output
// ... and stop.
console.timeEnd("flatten");

// Start timing now
console.time("flatten2");
output = [].concat.apply([], i)
output
// ... and stop.
console.timeEnd("flatten2");

// Start timing now
console.time("flatten3");
output = flattenArrayOfArrays(i)
output
// ... and stop.
console.timeEnd("flatten3");

我使用了这里最流行的答案和我的解决方案。我想有人会觉得这很有趣。干杯

另一个功能风格的ECMAScript 6解决方案:

声明函数:

const flatten = arr => arr.reduce(
  (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
);

并使用它:

flatten( [1, [2,3], [4,[5,[6]]]] ) // -> [1,2,3,4,5,6]

常量flatten=arr=>arr.reduce((a,b)=>a.oncat(Array.isArray(b)?压扁(b):b),[]);console.log(展平([1,[2,3],[4],[5],[6],[7,8,9],10],11],[12],13])

还可以考虑在最新版本的现代浏览器中提供的本机函数Array.prototype.flat()(针对ES6的建议)。感谢@(КонстантинВа)和@(Mark Amery)在评论中提到了这一点。

flat函数有一个参数,指定数组嵌套的预期深度,默认值为1。

[1, 2, [3, 4]].flat();                  // -> [1, 2, 3, 4]

[1, 2, [3, 4, [5, 6]]].flat();          // -> [1, 2, 3, 4, [5, 6]]

[1, 2, [3, 4, [5, 6]]].flat(2);         // -> [1, 2, 3, 4, 5, 6]

[1, 2, [3, 4, [5, 6]]].flat(Infinity);  // -> [1, 2, 3, 4, 5, 6]

设arr=[1,2,[3,4]];console.log(arr.flat());arr=[1,2,[3,4,[5,6]]];console.log(arr.flat());控制台日志(arr.flat(1));控制台日志(arr.flat(2));console.log(arr.flat(无限));

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

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

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

你可以使用Ramda JS flatten

var arr=[[1,2],[3],[4,5]];var flattedArray=R.flatten(arr);console.log(flattedArray)<script src=“https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js“></script>

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
}