Created
August 23, 2016 22:04
-
-
Save medelling24/4e96c2513ff8e11b321cd21daa4c38e2 to your computer and use it in GitHub Desktop.
flatten an array of arbitrarily nested arrays of integers into a flat array of integers
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
// [[1,2,[3]],4] | |
var arr = arrayFlatten([[1,2,[3]],4,[1,[2,[3]]]]); | |
console.log(arr); | |
//Main function | |
function arrayFlatten(obj){ | |
var flattenArray=[]; | |
//Call recursive funcion sending the array as "reference" | |
flatten(obj,flattenArray); | |
return flattenArray; | |
} | |
function flatten(obj, flattenArray){ | |
//If is an array, go for each element and call the same recursive function | |
if(isArray(obj)){ | |
obj.forEach(function(item){ | |
flatten(item,flattenArray); | |
}); | |
} | |
else{ | |
//is an integer, just push in the array | |
flattenArray.push(obj); | |
} | |
} | |
function isArray(obj) { | |
//Check if the object is an array | |
return Object.prototype.toString.call(obj) === '[object Array]'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment