1.对象键值对处理(推荐)
Array.prototype.myUnique = function () {
let _this =[...this],
obj = {};
for (let i = 0; i<_this.length;i++) {
let item = _this[i];
if(typeof obj[item] !== 'undefined') {
//当前这一项再数组中已经存在,我们把这一项在数组中干掉
_this[i] = _this[_this.length - 1];
_this.length --;
i--;
continue;
}
obj[item] = true;
}
obj = null;
return _this;
};
let ary = [1,2,3,4,2,1,23,4,4,3,5,2,1,2,3];
let uniqueAry = ary.myUnique();
console.log(uniqueAry);
2.排序后相邻去除法
把数组进行排序 ,验证当前项和后一项是否相同,如果不相同,说明没有重复,我们把相同项提取出来保存即可。
Array.prototype.myUnique = function () {
let _this =[],
ary = this.slice(0).sort((a,b) => a - b);
for (let i = 0; i<ary.length;i++) {
let item = ary[i],
next = ary[i + 1];
if (item !==next ) {
_this.push(item);
}
}
return _this;
};
let ary = [1,2,3,4,2,1,23,4,4,3,5,2,1,2,3];
let uniqueAry = ary.myUnique();
console.log(uniqueAry);
3.indexOf 获取当前项在数组中第一次出现位置的索引 (此方法不兼容IE6~8)
依次迭代数组中的每一项,验证当前项在数组中是否存在(不是和整个数组比较是否存在,而是和当前项的后面比较是否存在
Array.prototype.myUnique = function () {
let _this = [...this]
//依次迭代数组种的每一项,验证当前在数组中是否存在
for (let i = 0; i<_this.length;i++) {
let item = _this[i],
nextAry = _this.slice(i + 1);
if (nextAry.indexOf(item) >-1 ) {
_this[i] = _this[_this.length-1];
_this.length--;
i--;
}
}
return _this;
};
let ary = [1,2,3,4,2,1,23,4,4,3,5,2,1,2,3];
let uniqueAry = ary.myUnique();
console.log(uniqueAry);//[ 5, 23, 3, 4, 2, 1 ]