The following code
function steamrollArray(arr) {
// I\'m a steamroller, baby
return arr.flat();
}
steamrollArray([1, [2], [3, [[4]]]]);
Array.flat
is not supported by your browser. Below are two ways to implement it.
As a function, the depth
variable specifies how deep the input
array structure should be flattened (defaults to 1; use Infinity
to go as deep as it gets) while the stack
is the flattened array, passed by reference on recursive calls and eventually returned.
function flat(input, depth = 1, stack = [])
{
for (let item of input)
{
if (item instanceof Array && depth > 0)
{
flat(item, depth - 1, stack);
}
else {
stack.push(item);
}
}
return stack;
}
As a Polyfill, extending Array.prototype
if you prefer the arr.flat()
syntax:
if (!Array.prototype.flat)
{
Object.defineProperty(Array.prototype, 'flat',
{
value: function(depth = 1, stack = [])
{
for (let item of this)
{
if (item instanceof Array && depth > 0)
{
item.flat(depth - 1, stack);
}
else {
stack.push(item);
}
}
return stack;
}
});
}