我有一个JavaScript数组,如:

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

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

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

当前回答

let arr = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]];
arr = arr.reduce((a, b) => a.concat(b)); // flattened

其他回答


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"]);
Array.prototype.flatten = Array.prototype.flatten || function() {
    return [].reduce.call(this, function(flat, toFlatten) {
        return flat.concat(Array.isArray(toFlatten) ? toFlatten.flatten() : toFlatten);
    },[])
};

请注意:当使用Function.prototype.apply([].contat.apply([],arrays))或扩展运算符([].cantat(…arrays),以展平数组时,这两者都会导致大型数组的堆栈溢出,因为函数的每个参数都存储在堆栈上。

这里是一个以功能风格实现的堆栈安全实现,它将最重要的需求相互权衡:

可重用性可读性简洁表演

//小型、可重复使用的辅助功能:常量foldl=f=>acc=>xs=>xs.reduce(uncurry(f),acc);//aka减少常量未修正=f=>(a,b)=>f(a)(b);常量concat=xs=>y=>xs.contat(y);//使数组变平的实际函数-一个不言自明的单行:常量flatten=xs=>foldl(concat)([])(xs);//任意数组大小(直到堆爆炸:D)常量xs=[[1,2,3],[4,5,6],[7,8,9]];console.log(flatten(xs));//推导深度嵌套数组的递归解决方案现在很简单//更小型、可重复使用的辅助功能:const-map=f=>xs=>xs.map(apply(f));常量应用=f=>a=>f(a);const-isArray=Array.isArray;//导出的递归函数:const flattenr=xs=>flatten(map(x=>isArray(x)?flatnr(x):x)(xs));常量ys=[1,[2,[3,[4,[5],6,],7],8],9];控制台日志(flatnr(ys));

一旦您习惯了小箭头函数的通用形式、函数组合和更高阶的函数,这段代码读起来就像散文一样。然后,编程只包括将总是按预期工作的小构件组合在一起,因为它们不包含任何副作用。

function flatten(input) {
  let result = [];
  
  function extractArrayElements(input) {
    for(let i = 0; i < input.length; i++){
      if(Array.isArray(input[i])){
        extractArrayElements(input[i]);
      }else{
        result.push(input[i]);
      }
    }
  }
  
  extractArrayElements(input);
  
  return result;
}


// let input = [1,2,3,[4,5,[44,7,8,9]]];
// console.log(flatten(input));

// output [1,2,3,4,5,6,7,8,9]

适用于所有数据类型的递归版本

 /*jshint esversion: 6 */

// nested array for testing
let nestedArray = ["firstlevel", 32, "alsofirst", ["secondlevel", 456,"thirdlevel", ["theinnerinner", 345, {firstName: "Donald", lastName: "Duck"}, "lastinner"]]];

// wrapper function to protect inner variable tempArray from global scope;
function flattenArray(arr) {

  let tempArray = [];

  function flatten(arr) {
    arr.forEach(function(element) {
      Array.isArray(element) ? flatten(element) : tempArray.push(element);     // ternary check that calls flatten() again if element is an array, hereby making flatten() recursive.
    });
  }

  // calling the inner flatten function, and then returning the temporary array
  flatten(arr);
  return tempArray;
}

// example usage:
let flatArray = flattenArray(nestedArray);