我有一个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
其他回答
在javascript中定义一个名为foo的数组数组,并使用javascript的arrayconcat内置方法将该数组展平为单个数组:
const foo = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
console.log({foo});
const bar = [].concat(...foo)
console.log({bar});
应打印:
{ foo:
[ [ '$6' ],
[ '$12' ],
[ '$25' ],
[ '$25' ],
[ '$18' ],
[ '$22' ],
[ '$10' ] ] }
{ bar: [ '$6', '$12', '$25', '$25', '$18', '$22', '$10' ] }
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]
const arr = [1, 2, [3, 4]];
arr.reduce((acc, val) => acc.concat(val), []);
使用排列运算符:
常量输入=[[“$6”],[“$12”],【“$25”】,[“$25“],【”$18“】,【”$22“】,[”$10“]];常量输出=[].contat(…输入);console.log(输出);//-->["$6", "$12", "$25", "$25", "$18", "$22", "$10"]
您也可以尝试新的Array.flat()方法。其工作方式如下:
let arr=[[“$6”],[“$12”],【“$25”】,[“$25“],【”$18“】,【”$22“】,[”$10“]].flat()控制台日志(arr);
flat()方法创建一个新数组,所有子数组元素递归地连接到其中,直到1层深度(即数组内部的数组)
如果您还想展平三维或更高维度的数组,只需多次调用flat方法。例如(三维):
设arr=[1,2,[3,4,[5,6]]].flat().flat;控制台日志(arr);
小心!
Array.flat()方法相对较新。像ie这样的旧浏览器可能没有实现该方法。如果你想让你的代码在所有浏览器上运行,你可能需要将你的JS转换成一个旧版本。检查MDN web文档的当前浏览器兼容性。