Created
December 27, 2019 03:24
-
-
Save JaymesKat/026fbec0131d6b171206fefbd40310b6 to your computer and use it in GitHub Desktop.
Flatten a nested array, accounting for varying levels of nesting. Ref: freecodecamp
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
function steamrollArray(arr) { | |
let flatArr = []; | |
for(let item of arr){ | |
if(Array.isArray(item)){ | |
flatArr.push(...item.map(i => getValFromNestedArr(i))) | |
} | |
else { | |
flatArr.push(item) | |
} | |
} | |
return flatArr; | |
} | |
function getValFromNestedArr(arr){ | |
if(!Array.isArray(arr)){ | |
return arr; | |
} | |
else { | |
return getValFromNestedArr(arr[0]) | |
} | |
} | |
//Tests | |
steamrollArray([[["a"]], [["b"]]]) //should return ["a", "b"]. | |
steamrollArray([1, [2], [3, [[4]]]]) //should return [1, 2, 3, 4]. | |
steamrollArray([1, [], [3, [[4]]]]) //should return [1, 3, 4]. | |
steamrollArray([1, {}, [3, [[4]]]]) //should return [1, {}, 3, 4]. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment