Skip to content

Instantly share code, notes, and snippets.

@jonalvarezz
Created November 15, 2018 03:30
Show Gist options
  • Save jonalvarezz/2aefbef38051b0688f926d558edb5dc7 to your computer and use it in GitHub Desktop.
Save jonalvarezz/2aefbef38051b0688f926d558edb5dc7 to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers
/**
* Array Flat
* This a commonJS module written in ES6 that will flatten
* an array of arbitrarily nested arrays of
* integers into a flat array of integers.
*
* @example
* import arrayFlat from '/your/path/array-flat'
*
* flatten([0, 1, 3, [4, 5, 6, [4, 6]]])
* // -> [0, 1, 3, 4, 5, 6, 4, 6]
*
* @param Array
*/
const flat = (item, accum) => {
if (Array.isArray(item)) {
if (item.length === 0) {
return accum
}
item.forEach(i => flat(i, accum))
return accum;
} else {
accum.push(item)
return accum
}
}
function flatten (arr) {
if (!Array.isArray(arr)) return []
const output = flat(arr, [])
return output
}
export default flatten
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment