Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写flat #5

Open
coolpail opened this issue Nov 9, 2020 · 0 comments
Open

手写flat #5

coolpail opened this issue Nov 9, 2020 · 0 comments

Comments

@coolpail
Copy link
Owner

coolpail commented Nov 9, 2020

利用concat入参是数组时,相当于自动铺平一层

方法一:

function myFlat(arr) {
   let result = [];
   for(let i = 0; i < arr.length; i++) {
     if (Array.isArray(arr[i])) result = result.concat(myFlat(arr[i]))
     else result = result.concat(arr[i])
   }
   return result;
}

方法二:

function myFlat(arr) {
  return arr.reduce((p, n) => p.concat(Array.isArray(n) ? myFlat(n) : n), []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant