我有一个JavaScript数组,如:

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

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

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

当前回答

你可以使用Ramda JS flatten

var arr=[[1,2],[3],[4,5]];var flattedArray=R.flatten(arr);console.log(flattedArray)<script src=“https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js“></script>

其他回答

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
}

var arrays=[[“$6”],[“$12”],“$25”],【“$25“],【”$18“】,【”$22“】,“$10”】,【“$15”】,“$3”】,[”$3“],[”$75“],“$5”]、[”$100“]、[“$7”]、【”$3“]、【“$75”】、【”$5“]];var merged=[].contat.apply([],数组);警报(合并);

我只是在寻找一个更快更简单的解决方案,为什么?因为我是一个面试问题,我很好奇,所以我做了这个:

function flattenArrayOfArrays(a, r){
    if(!r){ r = []}
    for(var i=0; i<a.length; i++){
        if(a[i].constructor == Array){
            flattenArrayOfArrays(a[i], r);
        }else{
            r.push(a[i]);
        }
    }
    return r;
}

var i = [[1,2,[3]],4,[2,3,4,[4,[5]]]], output;

// Start timing now
console.time("flatten");
output = new Array(JSON.stringify(i).replace(/[^\w\s,]/g,"")); 
output
// ... and stop.
console.timeEnd("flatten");

// Start timing now
console.time("flatten2");
output = [].concat.apply([], i)
output
// ... and stop.
console.timeEnd("flatten2");

// Start timing now
console.time("flatten3");
output = flattenArrayOfArrays(i)
output
// ... and stop.
console.timeEnd("flatten3");

我使用了这里最流行的答案和我的解决方案。我想有人会觉得这很有趣。干杯

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

 /*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);

您可以使用Undercore:

var x = [[1], [2], [3, 4]];

_.flatten(x); // => [1, 2, 3, 4]