Skip to content

Instantly share code, notes, and snippets.

@rbrahul
Last active March 30, 2018 20:16
Show Gist options
  • Save rbrahul/c9ef5784d7c12e9c232b8769485c3ee3 to your computer and use it in GitHub Desktop.
Save rbrahul/c9ef5784d7c12e9c232b8769485c3ee3 to your computer and use it in GitHub Desktop.
Flaten Array using javascript
var originalArray = [1, [2], [3, 4, [5, [6,7]]]];
function flatten(arr) {
var flattenarr = [];
arr.forEach(item => {
if(Array.isArray(item)) {
var arrItem = item;
while(Array.isArray(arrItem)) {
arrItem.forEach(next => {
if(Array.isArray(next)) {
arrItem = next;
} else {
flattenarr.push(next);
arrItem = next;
}
});
}
} else {
flattenarr.push(item);
}
});
return flattenarr;
}
var newArray = flatten(originalArray);
console.log(newArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment