我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
深度扁平化和面向对象怎么样?
[23, [34, 454], 12, 34].flatten();
// --> [23,34, 454, 12, 34]
[23, [34, 454,[66,55]], 12, 34].flatten();
// --> [23, 34, 454, [66,55], 12, 34]
深压平:
[23, [34, 454,[66,55]], 12, 34].flatten(true);
// --> [23, 34, 454, 66, 55, 12, 34]
DEMO
CDN
如果所有数组元素都是Integer、Float,。。。或/和字符串,所以只需执行以下操作:
var myarr=[1,[7,[9.2]],[3],90];
eval('myarr=['+myarr.toString()+']');
print(myarr);
// [1, 7, 9.2, 3, 90]
DEMO
其他回答
Array.prototype.flatten = Array.prototype.flatten || function() {
return [].reduce.call(this, function(flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? toFlatten.flatten() : toFlatten);
},[])
};
要展平单个元素数组的数组,不需要导入库,简单的循环是最简单和最有效的解决方案:
for (var i = 0; i < a.length; i++) {
a[i] = a[i][0];
}
对反对选民:请阅读问题,不要因为它不适合你的不同问题而反对投票。对于所问的问题,此解决方案是最快和最简单的。
您可以使用Undercore:
var x = [[1], [2], [3, 4]];
_.flatten(x); // => [1, 2, 3, 4]
最好使用javascript reduce函数。
var arrays = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]];
arrays = arrays.reduce(function(a, b){
return a.concat(b);
}, []);
或者,使用ES2015:
arrays = arrays.reduce((a, b) => a.concat(b), []);
js小提琴
Mozilla文档
适用于所有数据类型的递归版本
/*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);