Bonfire 35: Steamroller

TASK: Flatten a nested array. You must account for varying levels of nesting.

I must admit I am still struggling with this stuff, but hey, it’s recursive and it works!
I’m much, much in debt to Jai’s solution on this thread.


function steamroller(arr) {


if (Array.isArray(arr) && arr.length > 0) {
var head = arr[0];
var tail = arr.slice(1);

return steamroller(head).concat(steamroller(tail));
} else {
return [].concat(arr);
}
};


steamroller([1, [2], [3, [[4]]]]);

Advertisements
Bonfire 35: Steamroller

One thought on “Bonfire 35: Steamroller

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s