Last active
March 30, 2018 20:16
-
-
Save rbrahul/c9ef5784d7c12e9c232b8769485c3ee3 to your computer and use it in GitHub Desktop.
Flaten Array using javascript
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
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