JS通过指定key对数组对象进行去重
《关于水群碰到水友要一个去重方法这件事》
unique = (array,key) => {
const _set = [...new Set(array.map(e => e[key]))];
let deArray = [];
_set.map(item=>{
deArray.push(array[array.findIndex(val=>val[key]===item)])
})
return deArray
}
测试用例:
unique([{name: 'a',id: 1}, {name: 'a',id: 2}, {name: 'b',id: 3}, {name: 'c',id: 4}, {name: 'c',id: 6}, {name: 'b',id: 6}, {name: 'd',id: 7}],'name')