Skip to content

Instantly share code, notes, and snippets.

@avaleriani
Created April 13, 2016 22:18
Show Gist options
  • Save avaleriani/5a0fc725aa18b41a74c1e77cd55de2b4 to your computer and use it in GitHub Desktop.
Save avaleriani/5a0fc725aa18b41a74c1e77cd55de2b4 to your computer and use it in GitHub Desktop.
Convert nested array into a flat one
//ES6
var flatten = {
makeFlat : function(arr) {
var res = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] instanceof Array) { //if the current position is an array then we keep looking for a value.
res.push.apply(res, this.makeFlat(arr[i])); //recursively calls makeFlat and concatenates with res.
} else {
res.push(arr[i]); //when is not an array, directly concatenate the value
}
}
return res;
},
test : function(){
console.log(this.makeFlat([1,2,3,4,[21,22,32,[55,66,[88]]]])))
}
};
module.exports = flatten;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment