Skip to content

Instantly share code, notes, and snippets.

@imolorhe
Created August 31, 2016 11:28
Show Gist options
  • Save imolorhe/9e18fdb61a757a1df233667f1a9c6fd2 to your computer and use it in GitHub Desktop.
Save imolorhe/9e18fdb61a757a1df233667f1a9c6fd2 to your computer and use it in GitHub Desktop.
Flatten array
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