Intermediate Algorithm Scripting: Steamroller
Flatten a nested array. You must account for varying levels of nesting.
const steamrollArray = arr =>
arr.reduce((acc, el) => acc.concat(Array.isArray(el) ? steamrollArray(el) : el), []);
[
steamrollArray([[["a"]], [["b"]]]),
steamrollArray([1, [2], [3, [[4]]]]),
steamrollArray([1, [], [3, [[4]]]]),
steamrollArray([1, {}, [3, [[4]]]])
].forEach(result => console.log(result));
Output:
[ 'a', 'b' ]
[ 1, 2, 3, 4 ]
[ 1, 3, 4 ]
[ 1, {}, 3, 4 ]
No comments:
Post a Comment