# JS去重总结
最近面试几次问到去重,回答的不是很好,总结下
# 双重循环
实现比较容易,代码略微繁琐
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;
}
# indexOf
- 利用
filter()
Array.prototype.unique = function () {
return this.filter((item, index) => {
return this.indexOf(item) === index;
})
}
forEach
Array.prototype.unique = function () {
const newArray = [];
this.forEach(item => {
if (newArray.indexOf(item) === -1) {
newArray.push(item);
}
});
return newArray;
}
# 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;
}
# reduce()
Array.prototype.unique = function () {
return this.sort().reduce((init, current) => {
if(init.length === 0 || init[init.length - 1] !== current){
init.push(current);
}
return init;
}, []);
}
# 键值对
利用对象key 不同
Array.prototype.unique = function () {
const newArray = [];
const tmp = {};
for (let i = 0; i < this.length; i++) {
if (!tmp[typeof this[i] + this[i]]) {
tmp[typeof this[i] + this[i]] = 1;
newArray.push(this[i]);
}
}
return newArray;
}
# includes()
Array.prototype.unique = function () {
const newArray = [];
this.forEach(item => {
if (!newArray.includes(item)) {
newArray.push(item);
}
});
return newArray;
}
# map()
Array.prototype.unique = function () {
const tmp = new Map();
return this.filter(item => {
return !tmp.has(item) && tmp.set(item, 1);
})
}
# set()
Array.prototype.unique = function () {
return [...new Set(this)];
}
# 总结
map
和set
去重速度快于其他方法,es5的方法兼容好一些