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

手写实现 lodash.flattenDeep 将array递归为一维数组【热度: 345】 #939

Open
yanlele opened this issue Sep 27, 2024 · 0 comments
Labels
web应用场景 应用场景类问题 小米 公司标签
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Sep 27, 2024

关键词:lodash.flattenDeep 实现

以下是用 JavaScript 手写实现类似于 lodash.flattenDeep 的函数来将数组递归展平为一维数组:

function flattenDeep(arr) {
  let result = [];
  for (let item of arr) {
    if (Array.isArray(item)) {
      result = result.concat(flattenDeep(item));
    } else {
      result.push(item);
    }
  }
  return result;
}

你可以使用以下方式测试这个函数:

const nestedArray = [1, [2, [3, [4]]]];
const flattenedArray = flattenDeep(nestedArray);
console.log(flattenedArray); // [1, 2, 3, 4]
@yanlele yanlele added web应用场景 应用场景类问题 小米 公司标签 labels Sep 27, 2024
@yanlele yanlele added this to the milestone Sep 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
web应用场景 应用场景类问题 小米 公司标签
Projects
None yet
Development

No branches or pull requests

1 participant