Created
September 13, 2016 03:56
-
-
Save rickMcGavin/0f0e197ea0063faa4b884e6a66612a22 to your computer and use it in GitHub Desktop.
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
// freecodecamp | |
// intermediate algorith scripting | |
// steamroller | |
function steamrollArray(arr) { | |
// create array to push non array items in to | |
var arr2 = []; | |
// create function that will flatten arrays | |
function flat(curr) { | |
// check if item being passed is an array | |
if (!Array.isArray(curr)) { | |
// if not -> push in to arr2 | |
arr2.push(curr); | |
// if item passed in to flat function is an array | |
} else { | |
// loop through each item of the array | |
curr.forEach(function(c) { | |
flat(c); // recursive call to flatten array | |
}); | |
} | |
} | |
// call flat function in each arr initally passed through streamrollArray function | |
arr.forEach(flat); | |
// return flattened array | |
return arr2; | |
} | |
// tests | |
console.log(steamrollArray([1, [2], [3, [[4]]]])); // returns [1, 2, 3, 4] | |
console.log(steamrollArray([[["a"]], [["b"]]])); // returns ["a", "b"] | |
console.log(steamrollArray([1, {}, [3, [[4]]]])); // returns [1, {}, 3, 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment