仅根据id判断
let arr1 = [
{id: 1, name:'a'},
{id: 2, name:'b'},
{id: 1, name:'a'},
{id: 3, name:'c'}]
let obj = {}
let res = arr1.reduce((prev, cur) => {
obj[cur.id] ? '' : obj[cur.id] = true && prev.push(cur)
return prev
},[])
姓名和性别相同才算重复
let arr2 = [
{name:'a',sex:'male'},
{name:'a',sex:'female'},
{name:'b',sex:'male'},
{name:'b',sex:'male'},
{name:'a',sex:'male'}
]
let obj2 = {}
let res2 = arr2.reduce((prev, cur) => {
obj2[Object.values(cur).join('')] ? '' : obj2[Object.values(cur).join('')] = true && prev.push(cur)
return prev
},[])
判断一个对象是否包含于另一个对象数组
function fn(arr, obj){
let keys = Object.keys(obj)
return arr.filter(item => {
for(let i = 0; i < keys.length; i++){
if(!item.hasOwnProperty(keys[i]) || item[keys[i]] != obj[keys[i]]) return false
}
return true
})
}
arr = [
{id: 1, name:'a'},
{id: 2, name:'b'},
{id: 3, name:'c'},
{id: 2, name:'b', sex: 'male'},
]
let a = fn(arr, {id:2, name:'b'})
console.log(a)//[{id: 2, name: "b"},{id: 2, name: "b", sex: "male"}]
普通数组去重
let arr = [3,25,25,36,36,12]
//方法1
let a = arr.filter((item,i) => arr.indexOf(item) == i)
//方法2
let b = [...new Set(arr)]
//方法3
let c = arr.reduce((prev, cur) =>{
if(!prev.includes(cur)){
prev.push(cur)
}
return prev
}, [])