Skip to content

Instantly share code, notes, and snippets.

@jeffheifetz
Created July 16, 2016 01:15
Show Gist options
  • Save jeffheifetz/b5c39982f53f57dc470881f0f6589d7d to your computer and use it in GitHub Desktop.
Save jeffheifetz/b5c39982f53f57dc470881f0f6589d7d to your computer and use it in GitHub Desktop.
Array flattener
'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