Skip to content

Instantly share code, notes, and snippets.

@elisavetTriant
Last active July 16, 2019 14:56
Show Gist options
  • Save elisavetTriant/81146e3aaac8432ef990e2567ca9f67a to your computer and use it in GitHub Desktop.
Save elisavetTriant/81146e3aaac8432ef990e2567ca9f67a to your computer and use it in GitHub Desktop.
/*Intermediate Algorithm Scripting: Steamroller
Flatten a nested array. You must account for varying levels of nesting.
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller
*/
function steamrollArray(arr) {
// I'm a steamroller, baby
let tempArray = [];
for (let i=0; i < arr.length; i++){
if (Array.isArray(arr[i])){
tempArray = tempArray.concat(steamrollArray(arr[i]))
} else {
tempArray.push(arr[i]);
}
}
return tempArray;
}
steamrollArray([1, [2], [3, [[4]]]]);
/*
steamrollArray([[["a"]], [["b"]]]) should return ["a", "b"].
Passed
steamrollArray([1, [2], [3, [[4]]]]) should return [1, 2, 3, 4].
Passed
steamrollArray([1, [], [3, [[4]]]]) should return [1, 3, 4].
Passed
steamrollArray([1, {}, [3, [[4]]]]) should return [1, {}, 3, 4].
Passed
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment