Skip to content

Instantly share code, notes, and snippets.

@arfianadam
Created August 24, 2017 04:54
Show Gist options
  • Save arfianadam/ca2fc81603c35c9116dcc78e2a151d50 to your computer and use it in GitHub Desktop.
Save arfianadam/ca2fc81603c35c9116dcc78e2a151d50 to your computer and use it in GitHub Desktop.
flatten nested array using javascript
const flatten = function(array, flattenArray = []) {
for (let i = 0; i < array.length; i++) {
const value = array[i];
if (Array.isArray(value)) {
flatten(value, flattenArray);
} else {
flattenArray.push(value);
}
}
return flattenArray;
};
const a = [1, [2, [3, 4, [5, [6, 7]]]], 8, 9];
console.log(flatten(a)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment