Created
January 6, 2017 02:10
-
-
Save daviseford/d552467dab998e2cbb03f80331351d6e to your computer and use it in GitHub Desktop.
Flatten arrays of arbitrary depths, bringing all integers to top level
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
'use strict'; | |
function flatten(array) { | |
let result = []; | |
const f = function (x) { | |
if (Array.isArray(x)) { | |
x.forEach((x) => { f(x) }); | |
} else if (typeof x === 'number') { | |
result.push(x) | |
} | |
}; | |
f(array); | |
return result; | |
} | |
assert flatten([]) === [] | |
assert flatten([[[[[[[[[[[[[[1]]]]]]]]]]]]]]) === [1] | |
assert flatten([[[3],[[[6,9]]]]]) === [3,6,9] | |
assert flatten([[4,5,'a','b'],[],[[[0]]]]) === [4,5,0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment