Skip to content

Instantly share code, notes, and snippets.

@JaymesKat
Created December 27, 2019 03:24
Show Gist options
  • Save JaymesKat/026fbec0131d6b171206fefbd40310b6 to your computer and use it in GitHub Desktop.
Save JaymesKat/026fbec0131d6b171206fefbd40310b6 to your computer and use it in GitHub Desktop.
Flatten a nested array, accounting for varying levels of nesting. Ref: freecodecamp
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