我有一个JavaScript数组,如:

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

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

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

当前回答

我认为array.flat(Infinity)是一个完美的解决方案。但平面功能是一个相对较新的功能,可能不会在旧版本的浏览器中运行。我们可以使用递归函数来解决这个问题。

常量arr=[“A”,[“B”,[[“B11”,“B12”,[”B131“,“B132”]],“B2”]],”C“,[”D“,”E“,”F“,[“G”,“H”,“I”]]]常量flatArray=(arr)=>{常量res=[]for(arr的常量项){if(Array.isArray(项)){const subRes=flatArray(项)资源推送(…subRes)}其他{res.push(项目)}}返回res}console.log(flatArray(arr))

其他回答

这是我的版本。它允许您将复杂的对象展平,可以在更多场景中使用:

输入

var input = {
   a: 'asdf',
   b: [1,2,3],
   c: [[1,2],[3,4]],
   d: {subA: [1,2]}
}

Code

功能如下:

function flatten (input, output) {

  if (isArray(input)) {
    for(var index = 0, length = input.length; index < length; index++){
      flatten(input[index], output);
    }
  }
  else if (isObject(input)) {
    for(var item in input){
      if(input.hasOwnProperty(item)){
        flatten(input[item], output);
      }
    }
  }
  else {
    return output.push(input);
  }
};

function isArray(obj) {
  return Array.isArray(obj) || obj.toString() === '[object Array]';
}

function isObject(obj) {
  return obj === Object(obj);
}

用法

var output = []

flatten(input, output);

输出

[“asdf”,1,2,3,1,2,3,4,1,2]

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

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引入了flat和flatMap,因此任何阵列都可以这样做:

const myArr = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
const myArrFlat= myArr.flat(Infinity);
console.log(myArrFlat); // ["$6", "$12", "$25", ...]

裁判。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

有一个新的本地方法叫做flat,可以准确地执行此操作。

(截至2019年底,flat现已发布在ECMA 2019标准中,并且core-js@3(babel的库)将其包含在他们的polyfill库中)

const arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

// Flatten 2 levels deep
const arr3 = [2, 2, 5, [5, [5, [6]], 7]];
arr3.flat(2);
// [2, 2, 5, 5, 5, [6], 7];

// Flatten all levels
const arr4 = [2, 2, 5, [5, [5, [6]], 7]];
arr4.flat(Infinity);
// [2, 2, 5, 5, 5, 6, 7];

我提出了两个没有递归的简短解决方案。从计算复杂性的角度来看,它们不是最优的,但在一般情况下工作良好:

let a = [1, [2, 3], [[4], 5, 6], 7, 8, [9, [[10]]]];

// Solution #1
while (a.find(x => Array.isArray(x)))
    a = a.reduce((x, y) => x.concat(y), []);

// Solution #2
let i = a.findIndex(x => Array.isArray(x));
while (i > -1)
{
    a.splice(i, 1, ...a[i]);
    i = a.findIndex(x => Array.isArray(x));
}