Last active
September 2, 2016 15:31
-
-
Save cmelgarejo/296fc2823406a7ad61b49d31ebb2dff4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| var arr = [[1,2,[3]],4,[5,[6.2]]]; | |
| var result = []; | |
| function flattenWithMap(array) { | |
| //Convert the array to a flat string, split it using commas, and map it using | |
| //the "Number" function to convert each element back to Integer :) | |
| if(array.constructor === Array) | |
| return array.toString().split(',').map(Number); | |
| else | |
| return array; | |
| } | |
| function flattenRecursive(elem, res) { | |
| if(elem.constructor === Array) //Checks if the element passed as the first parameter | |
| for(var i = 0; i < elem.length; i++) //traverses the array and looks for any nested arrays | |
| flattenRecursive(elem[i], res); //the second parameter that holds the result is passed along recursively | |
| else | |
| res.push(elem);// Pushes the integer into the result array | |
| return res; //returns the result array back up | |
| } | |
| console.log(flattenWithMap(arr)); | |
| console.log(flattenRecursive(arr, result)); | |
| //Code is a short essay (usually) written to the computer, which in turn reads it as an Ode, if done right ;) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment