Skip to content

Instantly share code, notes, and snippets.

@beaucharman
Last active May 23, 2016 23:27
Show Gist options
  • Save beaucharman/a16c90893fdaa37fb5775c3989262794 to your computer and use it in GitHub Desktop.
Save beaucharman/a16c90893fdaa37fb5775c3989262794 to your computer and use it in GitHub Desktop.
Recursively flatten a JS array
function recursiveFlatten(array, ignoreObjects = false) {
let current = []
const arrayLength = array.length
function isType(obj, type = 'Object') {
return Object.prototype.toString.call(obj).indexOf(type) !== -1
}
for (let i = 0; i < arrayLength; i++) {
let result
if (ignoreObjects && isType(array[i], 'Object' /* could use typeof array[i] === 'object' */)) {
continue
} else if (isType(array[i], 'Array') /* could use Array.isArray(array[i]) */) {
current = current.concat(recursiveFlatten(array[i]))
} else {
current.push(array[i])
}
}
return current
}
// usage
const array = [[1, 2, 3], { a: 2 }, [4, 5, 'hello', [45, [67, 89, 78, [11, 22, 33]]]], [6, 7, 8, 9]]
console.log(recursiveFlatten(array))
// > [1, 2, 3, { a: 2 }, 4, 5, "hello", 45, 67, 89, 78, 11, 22, 33, 6, 7, 8, 9]
console.log(recursiveFlatten(array, true))
// > [1, 2, 3, 4, 5, "hello", 45, 67, 89, 78, 11, 22, 33, 6, 7, 8, 9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment