Created
July 16, 2016 01:15
-
-
Save jeffheifetz/b5c39982f53f57dc470881f0f6589d7d to your computer and use it in GitHub Desktop.
Array flattener
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' | |
var input = [1, [2, 3, [4, [5], 6], 7, [8], 9], 10] | |
function flatten (array) { | |
let result = [] | |
if (!Array.isArray(array) || array.length === 0) { | |
return result | |
} | |
while (array.length > 0) { | |
let next = array.shift() | |
if (Array.isArray(next)) { | |
let subResult = flatten(next) | |
result = result.concat(subResult) | |
} else { | |
result.push(next) | |
} | |
} | |
return result | |
} | |
console.log(flatten(input)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment