Created
November 15, 2018 03:30
-
-
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
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
/** | |
* 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