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

第49题(2019-09-27):【编程题】已知数据结构users,请实现语法支持user.unique能够按照name字段去重,并输出结构为:["a","b"] #51

Open
qappleh opened this issue Sep 27, 2019 · 1 comment

Comments

@qappleh
Copy link
Owner

qappleh commented Sep 27, 2019

var users=[{
   id:1,name:"a"
},{
   id:2,name:"a"
},{
   id:3,name:"b"
},{
   id:4,name:"v"
}]
Array.prototype.unique = function () {
    var res;
    this.map(item => {
        this[item.id - 1] = item.name
    })
    // ES6里新添加了两个很好用的东西,set和Array.from
    // set是一种新的数据结构,它可以接收一个数组或者是类数组对象,自动去重其中的重复项目。
    res=new Set(this);
    console.log("new Set对象",res)
    // 但是这里大家可以看到,set返回的是一个对象,但是我们想要的是数组啊。
    // 这回,就该轮到Array.from出场了,它的作用,就是可以把类数组对象、可迭代对象转化为数组。
    res=Array.from(new Set(this));
    return  res//es6 数组去重
}
console.log(users.unique());  
@qappleh
Copy link
Owner Author

qappleh commented Sep 29, 2019

var users=[{
   id:1,name:"a"
},{
   id:2,name:"a"
},{
   id:3,name:"b"
},{
   id:4,name:"v"
}]
Array.prototype.unique = function () {
    var res;
    this.map(item => {
        this[item.id - 1] = item.name
    })
    // ES6里新添加了两个很好用的东西,set和Array.from
    // set是一种新的数据结构,它可以接收一个数组或者是类数组对象,自动去重其中的重复项目。
    res=new Set(this);
    console.log("new Set对象",res)
    // 但是这里大家可以看到,set返回的是一个对象,但是我们想要的是数组啊。
    // 这回,就该轮到Array.from出场了,它的作用,就是可以把类数组对象、可迭代对象转化为数组。
    res=Array.from(new Set(this));
    return  res//es6 数组去重
}
console.log(users.unique());  

运行图

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