Created
June 20, 2021 17:25
-
-
Save PachVerb/4fa9a89bb96a3aa845e0553a04f0ddd0 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
let isArray = (arr) => arr instanceof Array; | |
function flaten(arr) { | |
if (arr.length === 0) return arr; | |
// 1. 分解:先找数组 | |
if (isArray(arr)) { | |
arr.forEach((val) => { | |
flaten(val); | |
}); | |
} else { | |
curr.add(arr); | |
} | |
return curr; | |
} | |
// test | |
// arr = [1, 2, [3, [4]], 5]; | |
let res = flaten(arr) // ---> [1, 2, 3, 4, 5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
如果有更好的建议,欢迎留下宝贵的评论(If you have any better suggestions, please leave a comment :))