Created
December 3, 2015 02:55
-
-
Save anonymous/0c8f981234cdf59ea3a1 to your computer and use it in GitHub Desktop.
http://www.freecodecamp.com/nirajkrz 's solution for Bonfire: Steamroller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Bonfire: Steamroller | |
// Author: @nirajkrz | |
// Challenge: http://www.freecodecamp.com/challenges/bonfire-steamroller | |
// Learn to Code at Free Code Camp (www.freecodecamp.com) | |
//Flatten a nested array. You must account for varying levels of nesting. | |
function steamroller(arr) { | |
// I'm a steamroller, baby | |
var flattenedArray = []; | |
// Create function that adds an element if it is not an array. | |
// If it is an array, then loops through it and uses recursion on that array. | |
var flatten = function(arg) { | |
if (!Array.isArray(arg)) { | |
flattenedArray.push(arg); | |
} else { | |
for (var a in arg) { | |
flatten(arg[a]); | |
} | |
} | |
}; | |
// Call the function for each element in the array | |
arr.forEach(flatten); | |
return flattenedArray; | |
} | |
steamroller([1, [2], [3, [[4]]]]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment