Skip to content

Instantly share code, notes, and snippets.

@medelling24
Created August 23, 2016 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save medelling24/4e96c2513ff8e11b321cd21daa4c38e2 to your computer and use it in GitHub Desktop.
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
// [[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