我有一个JavaScript数组,如:

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

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

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

当前回答

最好是以递归的方式执行,这样如果另一个数组中还有另一个,就可以很容易地过滤。。。

const flattenArray = arr =>
  arr.reduce(
    (res, cur) =>
       !Array.isArray(cur) 
       ? res.concat(cur)
       : res.concat(flattenArray(cur)), []);

你可以这样称呼它:

flattenArray([[["Alireza"], "Dezfoolian"], ["is a"], ["developer"], [[1, [2, 3], ["!"]]]);

结果如下:

["Alireza", "Dezfoolian", "is a", "developer", 1, 2, 3, "!"]

其他回答

当您的数组中可能有一些非数组元素时,这是一种更一般情况的解决方案。

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;
}

您可以使用Undercore:

var x = [[1], [2], [3, 4]];

_.flatten(x); // => [1, 2, 3, 4]
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 flatten = function () {
  return [].slice.call(arguments).toString().split(',');
};

我建议使用节省空间的发电机功能:

函数*展平(arr){如果(!Array.isArray(arr))产生arr;否则为(设arr的el)屈服*展平(el);}//示例:console.log(…flatten([1,[2,[3,[4]]]));//1 2 3 4

如果需要,请创建一个展平值数组,如下所示:

let flattened = [...flatten([1,[2,[3,[4]]]])]; // [1, 2, 3, 4]