Last active
May 23, 2016 23:27
-
-
Save beaucharman/a16c90893fdaa37fb5775c3989262794 to your computer and use it in GitHub Desktop.
Recursively flatten a JS array
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
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