Created
August 31, 2016 11:28
-
-
Save imolorhe/9e18fdb61a757a1df233667f1a9c6fd2 to your computer and use it in GitHub Desktop.
Flatten array
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
function flatten(arr){ | |
var result = []; | |
// If arr not an array, then just return it | |
if(!isArray(arr))return arr; | |
for(var i = 0, len = arr.length; i < len; i++){ | |
var flattened = flatten(arr[i]); | |
if(isArray(flattened)){ | |
for(var j = 0, jlen = flattened.length; j < jlen; j++){ | |
// Could also use push() | |
result.push(flattened[j]); | |
} | |
} | |
else{ | |
result.push(flattened); | |
} | |
// result.concat(flatten(arr[i])); | |
} | |
return result; | |
} | |
function isArray(arr){ | |
return Object.prototype.toString.call(arr) === '[object Array]'; | |
} | |
// flatten([[1,2,[3]],4, [6, [7, [8, [9, 10, [11, 12, 13]]]]]]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment