Last active
April 14, 2016 17:20
-
-
Save adaam2/ad7d8b2bc3a8e8ee8452b3e0ef8be253 to your computer and use it in GitHub Desktop.
Flattening arrays (https://jsfiddle.net/vj6jvaxu/)
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 arr = [[1,2,[3]],4]; | |
// Call the method | |
var flattened = flatten(arr); | |
// Print the result out to the console.. | |
console.log(flattened); | |
function flatten(arr) { | |
var flatArray = []; | |
for(var i = 0; i < arr.length; i++) { | |
if(Array.isArray(arr[i])) { | |
// call this function recursively | |
var recursivelyFlattenedArray = flatten(arr[i]); | |
flatArray = flatArray.concat(recursivelyFlattenedArray); | |
} | |
else | |
{ | |
// Otherwise just add it to the main return value array! | |
flatArray.push(arr[i]); | |
} | |
} | |
// Return to the caller! | |
return flatArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment