Reputation: 502
I need to flatten multidimensional arrays but my code only flattens one array and then stops. What is wrong? How do I get it to only transfer the elements with no arrays.
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' ]
Upvotes: 1
Views: 190
Reputation: 11
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);
}
Upvotes: 0
Reputation: 12681
You're doing it right -- just missing a return
statement.
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']]]));
Upvotes: 1