我有一个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
其他回答
var arrays=[[“$6”],[“$12”],“$25”],【“$25“],【”$18“】,【”$22“】,“$10”】,【“$15”】,“$3”】,[”$3“],[”$75“],“$5”]、[”$100“]、[“$7”]、【”$3“]、【“$75”】、【”$5“]];var merged=[].contat.apply([],数组);警报(合并);
您可以继续使用Array.flat()方法来实现这一点,即使数组嵌套得更多。
[1,2,3,[2]].flat()
相当于
[1,2,3,[2]].flat(1)
所以当你的筑巢增加时,你可以继续增加数量。
eg:
[1,[2,[3,[4]]]].flat(3) // [1, 2, 3, 4]
如果您不确定嵌套的级别,可以只传递Infinity作为参数
[1,2,3,[2,[3,[3,[34],43],[34]]]].flat(Infinity) //[1, 2, 3, 2, 3, 3, 34, 43, 34]
最好使用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文档
我只使用ES6回答这个问题,假设深度阵列是:
const deepArray = ['1',[['a'],['b']],[2],[[[['4',[3,'c']]]],[5]]];
如果您知道或猜测阵列的深度不超过7这样的数字,请使用以下代码:
const flatArray = deepArray.flat(7);
但如果你不知道深度数组的深度,或者你的JavaScript引擎不支持像react原生JavaScriptCore那样的flat,请使用下面的JavaScript reduce函数:
const deepFlatten = arr =>
arr.reduce(
(acc, val) =>
Array.isArray(val)
? acc.concat(deepFlatten(val))
: acc.concat(val),
[]
);
这两种方法都返回以下结果:
["1", "a", "b", 2, "4", 3, "c", 5]
适用于所有数据类型的递归版本
/*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);