我有一个JavaScript数组,如:

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

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

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

当前回答

这并不难,只需遍历数组并合并它们:

var result = [], input = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"]];

for (var i = 0; i < input.length; ++i) {
    result = result.concat(input[i]);
}

其他回答

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 arr = [345,2,[34],2,[524,[5456]],[5456]];
var flat = arr.toString().split(',');

Works,在FF、IE和Chrome中还没有测试其他浏览器。

您可以使用Undercore:

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

_.flatten(x); // => [1, 2, 3, 4]
[1,[2,3],[4,[5,6]]].reduce(function(p, c) {
    return p.concat(c instanceof Array ? 
                    c.reduce(arguments.callee, []) : 
                    [c]); 
}, []);

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