我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
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]
其他回答
请注意:当使用Function.prototype.apply([].contat.apply([],arrays))或扩展运算符([].cantat(…arrays),以展平数组时,这两者都会导致大型数组的堆栈溢出,因为函数的每个参数都存储在堆栈上。
这里是一个以功能风格实现的堆栈安全实现,它将最重要的需求相互权衡:
可重用性可读性简洁表演
//小型、可重复使用的辅助功能:常量foldl=f=>acc=>xs=>xs.reduce(uncurry(f),acc);//aka减少常量未修正=f=>(a,b)=>f(a)(b);常量concat=xs=>y=>xs.contat(y);//使数组变平的实际函数-一个不言自明的单行:常量flatten=xs=>foldl(concat)([])(xs);//任意数组大小(直到堆爆炸:D)常量xs=[[1,2,3],[4,5,6],[7,8,9]];console.log(flatten(xs));//推导深度嵌套数组的递归解决方案现在很简单//更小型、可重复使用的辅助功能:const-map=f=>xs=>xs.map(apply(f));常量应用=f=>a=>f(a);const-isArray=Array.isArray;//导出的递归函数:const flattenr=xs=>flatten(map(x=>isArray(x)?flatnr(x):x)(xs));常量ys=[1,[2,[3,[4,[5],6,],7],8],9];控制台日志(flatnr(ys));
一旦您习惯了小箭头函数的通用形式、函数组合和更高阶的函数,这段代码读起来就像散文一样。然后,编程只包括将总是按预期工作的小构件组合在一起,因为它们不包含任何副作用。
此解决方案适用于任何深度级别(指定嵌套数组结构的深度)的数组。
function flatten(obj) {
var out = [];
function cleanElements(input) {
for (var i in input){
if (input[i]instanceof Array){
cleanElements(input[i]);
}
else {
out.push(input[i]);
}
}
}
cleanElements(obj);
return (out);
}
ES2019年
ES2019引入了Array.protocol.flat()方法,您可以使用它来展平阵列。它与大多数环境兼容,尽管它仅在Node.js版本11开始提供,而在Internet Explorer中根本不提供。
常量数组=[["$6"],["$12"],["$25"],["$25"],["$18"],["$22"],["$10"]];const merge3=arrays.flat(1)//指定嵌套数组结构应展平的深度级别。默认值为1。console.log(合并3);
较旧的浏览器
对于较旧的浏览器,可以使用Array.prototype.cocat合并数组:
var数组=[["$6"],["$12"],["$25"],["$25"],["$18"],["$22"],["$10"]];var merged=[].contat.apply([],数组);console.log(合并);
使用concat的apply方法将只将第二个参数作为数组,因此最后一行与此相同:
var merged = [].concat(["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]);
我已经使用递归和闭包完成了
function flatten(arr) {
var temp = [];
function recursiveFlatten(arr) {
for(var i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i])) {
recursiveFlatten(arr[i]);
} else {
temp.push(arr[i]);
}
}
}
recursiveFlatten(arr);
return temp;
}
使用那里的代码。
我会写:
myArray.enumerable().selectMany(function(x) { return x; }).array()