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

利用对象属性名的唯一性对数组去重 #5

Open
MY729 opened this issue Jul 19, 2019 · 0 comments
Open

利用对象属性名的唯一性对数组去重 #5

MY729 opened this issue Jul 19, 2019 · 0 comments

Comments

@MY729
Copy link
Owner

MY729 commented Jul 19, 2019

题目

利用对象属性名的唯一性对数组去重

解析

  1. 遍历数组,将数组的值作为对象的属性名
  2. 同时判断对象中是否已经存在该属性,如果不存在,取出这个数存在目标数组
  3. 输出目标数组

答案

let uniqueArr = (arr) => {
  let obj = {}
  let newArr = []
  arr.forEach(item => {
    if (!obj.hasOwnProperty(item)) {
      obj[item] = item
      newArr.push(item)
    }
  })
  return newArr
}

执行结果:

let arr = [1, 2, 2, 'a', 'a']
uniqueArr(arr) // 调用

// 输出
[1, 2, "a"]
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