Skip to content

Instantly share code, notes, and snippets.

@msmfsd
Last active July 16, 2018 08:53
Show Gist options
  • Save msmfsd/a07170859c88e9d18b1d2bd62059c711 to your computer and use it in GitHub Desktop.
Save msmfsd/a07170859c88e9d18b1d2bd62059c711 to your computer and use it in GitHub Desktop.
Flatten a n-dimensional nested Javascript array
/*
* Flatten deeply nested array without external library like Immutable
* Simplified ES6 version of lodash flattenDeep functionality
* Reference: https://lodash.com/docs#flattenDeep
* Requirements: Latest Chrome/FF browser or ES6 transpiler like Babel
*/
const INFINITY = 1 / 0
/*
* Utility flatten array function
* @param array: array
* @param depth : number
* @param isStrict : boolean
*/
const baseFlatten = (array, depth, result) => {
let index = -1
let length = array.length
result || (result = [])
while (++index < length) {
let value = array[index]
if (depth > 0 && Array.isArray(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, result)
} else {
result.push(value)
}
} else {
result.push(value)
}
}
return result;
}
/*
* Flatten a deep array function
* @param array : array
*/
const flattenDeep = (array) => {
const length = array ? array.length : 0
return length ? baseFlatten(array, INFINITY) : []
}
// test
const arr = [[1,2,[3]],4]
console.log(flattenDeep(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment