Created
April 13, 2016 22:18
-
-
Save avaleriani/5a0fc725aa18b41a74c1e77cd55de2b4 to your computer and use it in GitHub Desktop.
Convert nested array into a flat one
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
//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