我有一个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, "!"]

其他回答


ES2019年

ES2019引入了Array.protocol.flat()方法,您可以使用它来展平阵列。它与大多数环境兼容,尽管它仅在Node.js版本11开始提供,而在Internet Explorer中根本不提供。

常量数组=[["$6"],["$12"],["$25"],["$25"],["$18"],["$22"],["$10"]];const merge3=arrays.flat(1)//指定嵌套数组结构应展平的深度级别。默认值为1。console.log(合并3);


较旧的浏览器

对于较旧的浏览器,可以使用Array.prototype.cocat合并数组:

var数组=[["$6"],["$12"],["$25"],["$25"],["$18"],["$22"],["$10"]];var merged=[].contat.apply([],数组);console.log(合并);

使用concat的apply方法将只将第二个参数作为数组,因此最后一行与此相同:

var merged = [].concat(["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]);

制作平面阵列的方法

使用Es6 flat()使用Es6 reduce()使用递归使用字符串操作

[1,[2,[3,[4,[5,[6,7],8],9],10]]] - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

//使用Es6 flat()设arr=[1,[2,[3,[4,[5,[6,7],8],9],10]]]console.log(arr.flat(无限))//使用Es6 reduce()let flatIt=(array)=>array.reduce((x,y)=>x.concat(Array.isArray(y)?flatIt(y):y),[])console.log(flatIt(arr))//使用递归函数myFlat(数组){let flat=[].contat(…数组);返回flat.some(Array.isArray)?myFlat(平面):平面;}console.log(myFlat(arr));//使用字符串操作let strArr=arr.toString().split(',');for(设i=0;i<strArr.length;i++)strArr[i]=parseInt(strArr[i]);console.log(strArr)

此解决方案适用于任何深度级别(指定嵌套数组结构的深度)的数组。

function flatten(obj) {
    var out = [];
    function cleanElements(input) {
        for (var i  in input){
            if (input[i]instanceof Array){
                cleanElements(input[i]);
            }
            else {
                out.push(input[i]);
            }
        }
    }
    cleanElements(obj);
    return (out);
}

我只是尝试在不使用任何内置函数的情况下解决这个问题。

var arr = [1, 3, 4, 65, [3, 5, 6, 9, [354, 5, 43, 54, 54, 6, [232, 323, 323]]]];
var result = [];

function getSingleArray(inArr) {
  for (var i = 0; i < inArr.length; i++) {
    if (typeof inArr[i] == "object") {
      getSingleArray(inArr[i]); // Calling Recursively
    } else {
      result.push(inArr[i]);
    }
  }
}

getSingleArray(arr);
console.log(result); // [1, 3, 4, 65, 3, 5, 6, 9, 354, 5, 43, 54, 54, 6, 232, 323, 323]
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
}