html5 js 对象,关于html5:js-对象数组-去重

去重 函数unique

function unique(arr, key) {

if (!arr) return arr

if (key === undefined) return [...new Set(arr)]

const map = {

'string': e => e[key],

'function': e => key(e),

}

const fn = map[typeof key]

const obj = arr.reduce((o,e) => (o[fn(e)]=e, o), {})

return Object.values(obj)

}

一般数组去重

unique([1, 1, 1, 14, 1, 4, 4, 1, 13])

对象数组 去重

const list = [

{ id: 0, name: '小明', age: 13 },

{ id: 1, name: '小明', age: 99 },

{ id: 2, name: '小明', age: 23 },

{ id: 3, name: '小红', age: 42 },

{ id: 4, name: '小明', age: 13 },

{ id: 5, name: '小芳', age: 35 },

{ id: 0, name: '小明', age: 13 },

{ id: 7, name: '', age: 23 },

{ id: 8, name: 'lm', age: 22 },

{ id: 9, name: 'xh', age: 79 }

]

unique(list, 'id') // id 去重

unique(list, 'age') // age 去重

unique(list, 'name') // name 去重

unique(list, e => e.name + e.age) // name+age 去重

实现hashcode 去重

function hashcode(str) {

str = typeof str === 'object' ? JSON.stringify(str) : str

var hash = 0, i, chr, len;

if (str.length === 0) return hash;

for (i = 0, len = str.length; i < len; i++) {

chr = str.charCodeAt(i);

hash = ((hash << 5) - hash) + chr;

hash |= 0; // Convert to 32bit integer

}

return hash;

}

unique(list, e => hashcode(e)) // hashcode 去重

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值