我有一个JavaScript数组,如:

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

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

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

当前回答

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

输入

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]

其他回答

以下代码将压平深度嵌套的数组:

/**
 * [Function to flatten deeply nested array]
 * @param  {[type]} arr          [The array to be flattened]
 * @param  {[type]} flattenedArr [The flattened array]
 * @return {[type]}              [The flattened array]
 */
function flattenDeepArray(arr, flattenedArr) {
  let length = arr.length;

  for(let i = 0; i < length; i++) {
    if(Array.isArray(arr[i])) {
      flattenDeepArray(arr[i], flattenedArr);
    } else {
      flattenedArr.push(arr[i]);
    }
  }

  return flattenedArr;
}

let arr = [1, 2, [3, 4, 5], [6, 7]];

console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4, 5 ], [ 6, 7 ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7 ]

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

console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4 ], [ 5, 6, [ 7, 8, [Object] ] ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

另一个功能风格的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(无限));

泛型过程意味着我们不必在每次需要利用特定行为时重写复杂性。

concatMap(或flatMap)正是我们在这种情况下需要的。

//凹面::([a],[a])->[a]常量concat=(xs,ys)=>xs.concat(系统)//concatMap::(a->[b])->[a]->[b】常量concatMap=f=>xs=>xs.map(f).reduce(concat,[])//id::a->a常量id=x=>x(x)//展平::[[a]]->[a]常量展平=concatMap(id)//您的示例数据常量数据=[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]console.log(展平(数据))

远见

是的,你猜对了,它只会使一个层次变平,这正是它应该工作的方式

想象一下这样的数据集

//玩家::(字符串,数字)->玩家常量玩家=(姓名,号码)=>[姓名、编号]//team::(.Player)->团队const团队=(…玩家)=>玩家//游戏::(团队,团队)->游戏常量游戏=(teamA,teamB)=>[团队A,团队B]//样本数据常量团队A=团队(球员('ob',5),球员('lice',6))常量组B=团队(球员(“恶心”,4),球员(“朱利安”,2))常量游戏=游戏(A队、B队)console.log(游戏)//[[鲍勃,5],[爱丽丝,6],//[['ricky',4],['julian',2]]]

好的,现在假设我们要打印一份名册,显示所有将参加比赛的球员…

const gamePlayers = game =>
  flatten (game)

gamePlayers (game)
// => [ [ 'bob', 5 ], [ 'alice', 6 ], [ 'ricky', 4 ], [ 'julian', 2 ] ]

如果我们的展平过程也展平了嵌套数组,我们最终会得到这个垃圾结果…

const gamePlayers = game =>
  badGenericFlatten(game)

gamePlayers (game)
// => [ 'bob', 5, 'alice', 6, 'ricky', 4, 'julian', 2 ]

滚得很深,宝贝

这并不是说有时候你也不想压平嵌套的数组——只是这不应该是默认行为。

我们可以轻松地制作一个deepFlatten程序…

//凹面::([a],[a])->[a]常量concat=(xs,ys)=>xs.concat(系统)//concatMap::(a->[b])->[a]->[b】常量concatMap=f=>xs=>xs.map(f).reduce(concat,[])//id::a->a常量id=x=>x(x)//展平::[[a]]->[a]常量展平=concatMap(id)//deepFlatten::[[a]]->[a]恒定深度展平=凹面贴图(x=>Array.isArray(x)?深度展平(x):x)//您的示例数据常量数据=[0, [1, [2, [3, [4, 5], 6]]], [7, [8]], 9]console.log(展平(数据))// [ 0, 1, [ 2, [ 3, [ 4, 5 ], 6 ] ], 7, [ 8 ], 9 ]console.log(deepFlatten(数据))// [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

那里现在,每个作业都有一个工具——一个用于挤压一层嵌套、展平,另一个用于清除所有嵌套深度展平。

如果你不喜欢deepFlatten这个名字,也许你可以称之为毁灭或核武器。


不要重复两次!

当然,上面的实现是聪明和简洁的,但是使用.map后跟.reduce的调用意味着我们实际上要做的迭代超过了需要

使用我称之为mapReduce的可靠组合器,可以帮助将迭代保持在最小值;它采用一个映射函数m::a->b,一个归约函数r::(b,a)->b,并返回一个新的归约函数-这个组合子是换能器的核心;如果你感兴趣,我已经写了其他关于他们的答案

//mapReduce=(a->b,(b,a)->b,(a,b)->b)常量mapReduce=(m,r)=>(加速度,x)=>r(加速度,m(x))//concatMap::(a->[b])->[a]->[b】常量concatMap=f=>xs=>xs.reduce(mapReduce(f,concat),[])//凹面::([a],[a])->[a]常量concat=(xs,ys)=>xs.concat(系统)//id::a->a常量id=x=>x(x)//展平::[[a]]->[a]常量展平=concatMap(id)//deepFlatten::[[a]]->[a]恒定深度展平=凹面贴图(x=>Array.isArray(x)?深度展平(x):x)//您的示例数据常量数据=[ [ [ 1, 2 ],[ 3, 4 ] ],[ [ 5, 6 ],[ 7, 8 ] ] ]console.log(展平(数据))// [ [ 1. 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ] ]console.log(deepFlatten(数据))// [ 1, 2, 3, 4, 5, 6, 7, 8 ]

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

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

如果只有一个字符串元素的数组:

[["$6"], ["$12"], ["$25"], ["$25"]].join(',').split(',');

将完成这项工作。与您的代码示例具体匹配的Bt。