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

JavaScript之数组去重 #13

Open
chenyong9528 opened this issue Aug 28, 2020 · 0 comments
Open

JavaScript之数组去重 #13

chenyong9528 opened this issue Aug 28, 2020 · 0 comments

Comments

@chenyong9528
Copy link
Owner

第一种

const clearDup = (arr) => {
  return arr.filter((v, i) => {
    return arr.indexOf(v) === i
  })
}

通过遍历数组的每一项,判断当前项第一次出现的位置和当前项的位置来判断是否重复

第二种

const clearDup = (arr) => {
  const result = []

  for (const v of arr) {
    if (!result.includes(v)) result.push(v)
  }

  return result
}

与第一种不同之处在于,判断的是当前项是否存在结果的数组中,如果不存在就添加到结果中

第三种

const clearDup = (arr) => {
  return [...new Set(arr)]
}

这种方式非常简单,利用了数据类型Set不会出现重复值的特点

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

No branches or pull requests

1 participant