说明:以下代码如有考虑不周的bug请评论区留言,我将不断完善或者优化,谢谢
const arr = [
{ id: 1, name: "数据1" },
{ id: 1, name: "数据2" },
{ id: 2, name: "数据3" },
{ id: 3, name: "数据4" },
{ id: 4, name: "数据5" },
{ id: 3, name: "数据6" },
{ id: 5, name: "数据7" },
{ id: 5, name: "数据7",arr:[1,2],arr1:[1,4] },
{ name: "数据7",id: 5,arr1:[1,4],arr:[1,2] },
{ name: "数据7",id: 5,arr:[1,2,3] },
[1,2,3,[1,'df'], { id: 1, name: "数据1" },],
[1,2,3,[1,'df'], { id: 2, name: "数据1" },],
[1,2,3,[1,2]],1,1
]
console.log('last:',deduplicate(arr))
function deduplicate(arr) {
if(!Array.isArray(arr)){
console.log('请传入正确的数组')
return
}else{
if(arr.length<2){
return arr
}
let newArr = arr.reduce((pre,next)=>{
let isHas = pre.some(item1=>isEquals(item1,next))
if(!isHas){
pre.push(next)
}
return pre
},[arr[0]])
return newArr
}
}
function getType(data){
return Object.prototype.toString.call(data).slice(8,-1)
}
function isEquals(data1,data2){
let type1 = getType(data1)
let type2 = getType(data2)
if(type1!==type2){
return false
}
if(type1==='Object'){
if(Object.keys(data1).length!==Object.keys(data2).length){
return false
}else{
for(let key in data1){
if(!data2.hasOwnProperty(key)){
return false
}else if(!isEquals(data1[key],data2[key])){
return false
}
}
}
return true
}
if(type1==='Array'){
if(data1.length!==data2.length){
return false
}else{
for(let i=0;i<data1.length;i++){
if(!isEquals(data1[i],data2[i])){
return false
}
}
}
return true
}else{
return data1 === data2
}
}