Skip to content

Instantly share code, notes, and snippets.

@PachVerb
Created June 20, 2021 17:25
Show Gist options
  • Save PachVerb/4fa9a89bb96a3aa845e0553a04f0ddd0 to your computer and use it in GitHub Desktop.
Save PachVerb/4fa9a89bb96a3aa845e0553a04f0ddd0 to your computer and use it in GitHub Desktop.
扁平化嵌套数组
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]
@PachVerb
Copy link
Author

如果有更好的建议,欢迎留下宝贵的评论(If you have any better suggestions, please leave a comment :))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment