我需要展平多维数组,但我的代码只展平一个数组,然后停止。怎么了?如何让它只传输没有数组的元素。
function flatten(arr) {
// I'm a steamroller, baby
arr.reduce(function (flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
},[]);
}
flatten([[['a']], [['b']]]);
assert.deepEqual(flatten([[['a']], [['b']]]), ['a', 'b'], 'should flatten nested arrays');
should flatten nested arrays: expected [ [ 'a' ], [ 'b' ] ] to deeply equal [ 'a', 'b' ]
您做得很好——只是缺少一个return
语句。
function flatten(arr) {
// I'm a steamroller, baby
return arr.reduce(function (flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
}
console.log(flatten([[['a']], [['b']]]));
let myarray = [
1000,
[1, 2, 3, 4],
[5, 6, 7],
[999, [10, 20, [100, 200, 300, 400], 40], [50, 60, 70]],
];
function f(array) {
let result = [];
function flatten(array) {
for (let i = 0; i < array.length; i++) {
if (!Array.isArray(array[i])) {
result.push(array[i]);
} else {
flatten(array[i]);
}
}
return result;
}
return flatten(array);
}