1.对象键值对
原理:利用了对象的key不可以重复的特性来进行去重。
var arr=[0,0,1,2,2,3,4,4,4];
Array.prototype.unique=function(){
var temp={},
arr=[],
len=this.length;
for(var i=0;i<len;i++){
if(!temp[this[i]]){
temp[this[i]]='abc';
arr.push(this[i]);
}
}
return arr;
}
2.双重循环方法
Array.prototype.unique=function(){
const newArray=[];
let isRepeat;
for(let i=0;i<this.length;i++){
isRepeat=false;
for(let j=0;j<newArray.length;j++){
if(this[i]===newArray[j]){
isRepeat=true;
break;
}
}
if(!isRepeat){
newArray.push(this[i]);
}
}
return newArray;
}
3.利用valueof的功能
let arr = [1, 2, 3, 22, 233, 22, 2, 233, 'a', 3, 'b', 'a'];
Array.prototype.unique = function () {
const newArray = [];
this.forEach(item => {
if (newArray.indexOf(item) === -1) {
newArray.push(item);
}
});
return newArray;
}
4.sort方法
Array.prototype.unique = function () {
const newArray = [];
this.sort();
for (let i = 0; i < this.length; i++) {
if (this[i] !== this[i + 1]) {
newArray.push(this[i]);
}
}
return newArray;
}
5.includes方法
Array.prototype.unique = function () {
const newArray = [];
this.forEach(item => {
if (!newArray.includes(item)) {
newArray.push(item);
}
});
return newArray;
}
6.map方法
Array.prototype.unique = function () {
const newArray = [];
const tmp = new Map();
for(let i = 0; i < this.length; i++){
if(!tmp.get(this[i])){
tmp.set(this[i], 1);
newArray.push(this[i]);
}
}
return newArray;
}