需要去重的数组:
let arr = [{a:1,b:2,c:3},{b:2,c:3,a:1},{d:2,c:2},{d:2,c:2},1,1,[1],[1],[],[],{},{},undefined,undefined,null,null]
输出为最终结果为:
{ a: 1, b: 2, c: 3 },
{ c: 2, d: 2 },
1,
[ 1 ],
[],
{},
undefined,
null
]
其中{a:1,b:2,c:3},{b:2,c:3,a:1},内容相同但顺序不同,需要去重。
具体代码如下:
function sort(obj){
// if(Array.isArray(obj))
if(obj == null){
return JSON.stringify(obj)
}else{
let newObj = {}
Object.keys(obj).sort().map((key)=>{
newObj[key] = obj[key]
})
// 将排序好的数组转成字符串
return JSON.stringify(newObj)
}
}
function unique(arr){
let set = new Set()
for(let i in arr){
if((!Array.isArray(arr[i])) && typeof arr[i] === 'object'){
let str = sort(arr[i])
set.add(str)
}
else{
set.add(JSON.stringify(arr[i]))
// set.add(arr[i])
}
}
arr = [...set].map(item => {
if(item === undefined ) return item //undeined无法解析回对象
//将数组中的字符串转回对象
return JSON.parse(item)
})
return arr
}