/**
* 数组对象去重
* @param arr 需要去重的数组
* @param property 根据哪个属性去重
*/
function arrRemove(arr, property){
let hash = {}
let arrData = arr.reduce((arrNow, cut) => {
hash[typeof cut[property] + cut[property]]
? ''
: (hash[typeof cut[property] + cut[property]] = true && arrNow.push(cut))
return arrNow
}, [])
return arrData
}
let arr = [
{id:0},{id:1},{id:undefined},{id:null},{id:true},{id:'true'}
,{id:0},{id:1},{id:undefined},{id:null},{id:true},{id:'true'}
,{id:NaN},{id:'NaN'},{id:'1'},{id:{}},{id:false},{id:'false'},{id:'0'}
,{id:NaN},{id:'NaN'},{id:'1'},{id:{}},{id:false},{id:'false'},{id:'0'}
];
console.log(arrRemove(arr, 'id'));
//打印输出
/*
0: {id: 0}
1: {id: 1}
2: {id: undefined}
3: {id: null}
4: {id: true}
5: {id: 'true'}
6: {id: NaN}
7: {id: 'NaN'}
8: {id: '1'}
9: {id: {}}
10: {id: false}
11: {id: 'false'}
12: {id: '0'}
*/
Javascript 数组中的对象如何去重
于 2021-12-23 16:05:47 首次发布