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方法【热度: 244】 #601

Open
yanlele opened this issue Oct 21, 2023 · 0 comments
Open

[代码实现] 手写数组降维flat方法【热度: 244】 #601

yanlele opened this issue Oct 21, 2023 · 0 comments
Labels
代码实现/算法 代码实现或者算法实现 阿里巴巴 公司标签
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Oct 21, 2023

关键词:JS数组降维、reduce数组降维

原生Array.prototype.flat方法接受一个depth参数,默认值为1,depth表示要降维的维数:

输出结果:

const arr = [1, [2, 3], [4, [5, 6]]]
console.log(arr.flat(1))         // [1, 2, 3, 4, [5, 6]]
console.log(arr.flat(Infinity))  // [1, 2, 3, 4, 5, 6]

reduce + 递归实现方案

// MDN: 可查看更多flat实现方法
function flat(arr = [], depth = 1) {
  if (arr.length === 0) {
    return []
  }
  let result = []
  if (depth > 0) {
    result = arr.reduce((acc, val) => {
      return acc.concat(Array.isArray(val) ? flat(val, depth - 1) : val)
    }, [])
  } else {
    result = arr.slice()
  }
  return result
}

const arr = [1, 2, 3, [1, 2, 3, 4, [2, 3, 4]]]
const myResult1 = flat(arr, 1)
const originResult1 = arr.flat(1)
const myResult2 = flat(arr, Infinity)
const originResult2 = arr.flat(Infinity)
console.log(myResult1)      // [1, 2, 3, 1, 2, 3, 4, [2, 3, 4]]
console.log(originResult1)  // [1, 2, 3, 1, 2, 3, 4, [2, 3, 4]]
console.log(myResult2)     // [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
console.log(originResult2) // [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
@yanlele yanlele added 代码实现/算法 代码实现或者算法实现 阿里巴巴 公司标签 labels Oct 21, 2023
@yanlele yanlele added this to the milestone Oct 21, 2023
@yanlele yanlele changed the title 手写数组降维flat方法【热度: 244】 [代码实现] 手写数组降维flat方法【热度: 244】 Oct 21, 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