Skip to content

Instantly share code, notes, and snippets.

@sunguru98
Last active January 23, 2020 09:57
Show Gist options
  • Save sunguru98/2f3ba755bc3b3d92b161762ebcf78592 to your computer and use it in GitHub Desktop.
Save sunguru98/2f3ba755bc3b3d92b161762ebcf78592 to your computer and use it in GitHub Desktop.
Flatten an array without using flat method.
const flattenArray = nestedArr => {
// Checking for the emptiness of array
if (!nestedArr.length) return null;
// Creating a new array for every recursive call
const newArr = [];
// If the current element is an array, we recursively call the function and then push the values present in the returned array.
// Else we just push the current element on to the new Array.
nestedArr.forEach(el =>
Array.isArray(el) ? newArr.push(...flattenArray(el)) : newArr.push(el)
);
// Finally we return the array to continue the recursion, or exit from the final call stack.
return newArr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment