测试数据:
let arr1 = [3, 1, [1], 1, [1], true, true, {}, '1', NaN, undefined, NaN, undefined, {}, null, null,new String('1'),new String('1')];
1. 两种for循环 + splice(耗时最长)不能正确去重NaN和Object的方法
Array.prototype.unique = function () {
for (let i = 0; i < this.length; i++) {
for (let j = i + 1; j < this.length; j++) {
if (this[i] === this[j]) {
this.splice(j, 1);
j--;
}
}
}
return this;
}
2. forEach + indexOf 不能正确去重NaN和Object的方法
Array.prototype.unique = function () {
let newArr = [];
this.forEach((item) => {
if (newArr.indexOf(item) === -1) {
newArr.push(item);
}
})
return newArr;
}
4. for + sort(sort有问题)带 sort 方法的只对纯number或者纯string类型有效,它无法区分1和'1',
因为它是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的。
Array.prototype.unique = function () {
let newArr = [];
this.sort();
for (let i = 0; i < this.length; i++) {
if (this[i] !== this[i + 1]) {
newArr.push(this[i]);
}
}
return newArr;
}
5. forEach + includes 能正确去重NaN,不能去重复杂数据类型
Array.prototype.unique = function () {
let newArr = [];
this.forEach((item) => {
if (!newArr.includes(item)) {
newArr.push(item);
}
})
return newArr;
}
6. forEach + map 能正确去重NaN,不能去重复杂数据类型
Array.prototype.unique = function () {
let map = new Map();
let newArr = new Array();
this.forEach((item) => {
if (!map.has(item)) {
map.set(item, 1);
newArr.push(item);
}
});
return newArr;
}
7. Set 可以去掉重复的NaN,但是不能去掉重复的复杂数据类型
Array.prototype.unique = function () {
return [...new Set(this)];
}
8. filter + hasOwnProperty + JSON.stringify 可以去掉重复的NaN,重复的复杂数据类型,但是不能去掉正则表达式,还会丢失正则表达式
Array.prototype.unique = function () {
let obj = {};
return this.filter(function (item, index, arr) {
return obj.hasOwnProperty(typeof item + JSON.stringify(item)) ? false : (obj[typeof item + JSON.stringify(item)] = true);
});
}
9. filter + hasOwnProperty + JSON.stringify 可以去掉重复的NaN,重复的复杂数据类型,正则表达式
Array.prototype.unique = function () {
let obj = {};
return this.filter(function (item, index, arr) {
let key = typeof item + JSON.stringify(item)+item;
return obj.hasOwnProperty(key) ? false : (obj[key] = true);
});
}