我有一个JavaScript数组,如:

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

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

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

当前回答

在javascript中定义一个名为foo的数组数组,并使用javascript的arrayconcat内置方法将该数组展平为单个数组:

const foo = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]] 
console.log({foo}); 

const bar = [].concat(...foo) 
console.log({bar});

应打印:

{ foo: 
   [ [ '$6' ],
     [ '$12' ],
     [ '$25' ],
     [ '$25' ],
     [ '$18' ],
     [ '$22' ],
     [ '$10' ] ] }
{ bar: [ '$6', '$12', '$25', '$25', '$18', '$22', '$10' ] }

其他回答

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

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

只有没有lodash的最佳解决方案

let flatten = arr => [].concat.apply([], arr.map(item => Array.isArray(item) ? flatten(item) : item))

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

输入

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]

我认为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 multipleArrays = [["$6","$Demo"], ["$12",["Multi","Deep"]], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]]

var flattened = multipleArrays.join().split(",")

此解决方案适用于多个级别,也是一个线性解决方案。

DEMO

ECMAScript 6的EDIT

由于ECMAScript 6已经标准化,您可以更改操作[].contat.apply([],arrays);对于[].contat(…数组);

var flattened = [].concat(...input);

DEMO

EDIT最高效的解决方案

解决这个问题最有效的方法是使用循环。您可以在此处比较“ops/sec”速度

var flattened=[];
for (var i=0; i<input.length; ++i) {
    var current = input[i];
    for (var j=0; j<current.length; ++j)
        flattened.push(current[j]);
} 

DEMO

希望有帮助