Created
April 22, 2018 04:05
-
-
Save HuangXiZhou/3a26ec56ee1f1b6d2690f2ec37c607f4 to your computer and use it in GitHub Desktop.
JavaScript Arrary flat functions
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
// Use recursion | |
function flatten(arr) { | |
let result = []; | |
arr.forEach(el => { | |
if (el instanceof Array) { | |
result = result.concat(flatten(el)); | |
} else { | |
result.push(el); | |
} | |
}); | |
return result; | |
} | |
// Without use recursion | |
function flatten(arr) { | |
while (arr.some(item => Array.isArray(item))) { | |
arr = [].concat(...arr); | |
} | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment