Created
November 14, 2017 00:55
-
-
Save JeffCave/45bc3a0e3fb57c0506533df7ea9fa36d to your computer and use it in GitHub Desktop.
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
/** | |
* Flatten nested arrays. | |
* | |
* @param {array} arr - The nested array to be flattened | |
* @param {number} failsafe - (Optional) In case of extreme depth, simply stops the recursion | |
*/ | |
function FlattenArray(arr, failsafe){ | |
if(typeof failsafe === 'undefined'){ | |
failsafe = Number.MAX_SAFE_INTEGER; | |
//failsafe = 1 | |
} | |
//console.log(failsafe); | |
if(failsafe === 0) return []; | |
failsafe--; | |
return arr.reduce((a,elem)=>{ | |
if(Array.isArray(elem)){ | |
elem = FlattenArray(elem, failsafe); | |
} | |
else{ | |
elem = [elem]; | |
} | |
while(elem.length > 0){ | |
a.push(elem.shift()); | |
} | |
return a; | |
},[]); | |
} | |
//Test code | |
arr = [[1,2,[3]],4]; | |
arr = FlattenArray(arr); | |
arr = JSON.stringify(arr) | |
console.log(arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment