- 使用
new Set(arr)
包含对象,去重效果不好
var arr = [1, 1, 'true', 'true', true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,'NaN', 0, 0, 'a', 'a', {}, {}];
console.log([...new Set(arr)]);
- 使用
obj.hasOwnProperty()
包含对象,去重效果不好
function unique(arr) {
var obj = {};
return arr.filter(function(item, index, arr) {
return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)
})
}
var arr = [1, 1, 'true', 'true', true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,'NaN', 0, 0, 'a', 'a', {}, {}, {name: 1}, {name: 2}, {name: 1,}];
console.log(unique(arr))
var arr = [1, 1, 'true', 'true', true, true, 15, 15, false, false, undefined, undefined, null, null, NaN,NaN,'NaN', 0, 0, 'a', 'a', {}, {}, {name: 2},{name: 1}];
console.log(arrDuplicateRemoval(arr))
function arrDuplicateRemoval(arr = []) {
if(!Array.isArray(arr) || arr.length <= 0) return "请传入数组";
var obj = {}, objArr = [];
return arr.filter(item => {
if(item && typeof item === "object" && !Array.isArray(item)) {
var identical = true
objArr.forEach((objItem) => objIdentical(objItem, item) || (identical = false))
identical && objArr.push(item);
return identical
}
return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true);
})
}
function objIdentical(obj1, obj2) {
if( Array.isArray(obj1) || Array.isArray(obj2) || typeof obj1 !== "object" || typeof obj2 !== "object") return true
arrKey1 = Object.keys(obj1);
if(arrKey1.length !== Object.keys(obj2).length) return true
for(let i = 0; i < arrKey1.length; i++) {
if(obj1[arrKey1[i]] !== obj2[arrKey1[i]]) return true
}
return false
}