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方法,支持深度层级参数 #461

Open
yanlele opened this issue Jun 14, 2023 · 0 comments
Open

[代码实现] 实现数组的flat方法,支持深度层级参数 #461

yanlele opened this issue Jun 14, 2023 · 0 comments
Labels
京东 公司标签 代码实现/算法 代码实现或者算法实现
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Jun 14, 2023

可以通过传入一个深度参数来限制 flat 方法的递归深度。实现如下:

function flat(arr, depth = 1) {
  let res = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i]) && depth > 0) {
      res = res.concat(flat(arr[i], depth - 1));
    } else {
      res.push(arr[i]);
    }
  }
  return res;
}

这里在原有的 flat 方法基础上增加了一个 depth 参数,每递归一层,深度就减一,当深度为 0 时就不再递归。

@yanlele yanlele added JavaScript JavaScript 语法部分 京东 公司标签 labels Jun 14, 2023
@yanlele yanlele added this to the milestone Jun 14, 2023
@yanlele yanlele changed the title 实现数组的flat方法,支持深度层级参数 [代码实现] 实现数组的flat方法,支持深度层级参数 Sep 6, 2023
@yanlele yanlele added 代码实现/算法 代码实现或者算法实现 and removed JavaScript JavaScript 语法部分 labels Sep 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
京东 公司标签 代码实现/算法 代码实现或者算法实现
Projects
None yet
Development

No branches or pull requests

1 participant