思路就是通过index去动态匹配数组中每一项的key是否重复
var myarry = [
{name: 'zhangsan',age :20},
{name:'lisi',age:13},
{name:'wangwu',age:18},
{name:'jake',age:17},
{name:'lisi',age:24} ]
// 传入数组和去重的key如name
function deweight (arr, key) {
let res = []
arr.forEach((item) => {
let list = []
res.forEach((resitem) => {
list.push(resitem[key])
})
if (list.indexOf(item[key]) === -1) {
res.push(item)
}
})
return res
}
var result = deweight(myarry,'name')
console.log(result)
结果:
[ {name: 'zhangsan',age :20},
{name:'lisi',age:13},
{name:'wangwu',age:18},
{name:'jake',age:17}, ]