Skip to content

Instantly share code, notes, and snippets.

Created December 3, 2015 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/0c8f981234cdf59ea3a1 to your computer and use it in GitHub Desktop.
Save anonymous/0c8f981234cdf59ea3a1 to your computer and use it in GitHub Desktop.
http://www.freecodecamp.com/nirajkrz 's solution for Bonfire: Steamroller
// 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