Skip to content

Instantly share code, notes, and snippets.

Last active September 23, 2017 00:43
What would you like to do?
flattens a nested array of integers at any depth
* flattenNested - Reduces an array of arbitrarily nested arrays of integers into a flat array of integers.
* @param value {Array} - The array to flatten.
* @param iterator {Array} - An array used for initializing or for iteration during recursion.
* @returns {Array} - The flattened array, yay!
function flattenNested(value, iterator = []) {
// Add exit case straight away to help prevent stack overflow
if (!value) return iterator;
// Ensure that the value is an array before calling prototype methods on it
for (item of value) {
if (Array.isArray(item)) {
// Flatten nested array using recursion
flattenNested(item, iterator);
} else {
// Push the item onto the iterator
return iterator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment