今天,刚刚参加了公司的笔试,关于数组去重,后来简单总结了几种方法,希共勉,为我打call.......
es5四种方式:
方式一:
Array.prototype.unique1 = function() {
// 1. 定义数组
var temp = [];
// 2. 遍历当前数组
for(var i = 0; i < this.length; i++) {
// 3.如果当前数组的第i已经保存进了临时数组,
// 那么跳过,否则把当前项push到临时数组里面
if (-1 === temp.indexOf(this[i])) {
temp.push(this[i]);
}
}
return temp;
};
方式二:
Array.prototype.unique2 = function() {
//1. hash为hash表,r为临时数组
var hash = {}, temp=[];
// 2.遍历当前数组
for(var i = 0; i < this.length; i++)
{
// 3. 如果hash表中没有当前项
if (!hash[this[i]])
{
// 4.存入hash表
hash[this[i]] = true;
// 5.把当前数组的当前项push到临时数组里面
temp.push(this[i]);
}
}
return temp;
};
方式三:
Array.prototype.unique3 = function() {
var n = [this[0]];
for(var i = 1; i < this.length; i++){
if (this.indexOf(this[i]) === i) {
n.push(this[i]);
}
}
return n;
};
方式四:
Array.prototype.unique4 = function() {
this.sort();
var re=[this[0]];
for(var i = 1; i < this.length; i++)
{
if( this[i] !== re[re.length-1])
{
re.push(this[i]);
}
}
return re;
};
es6实现方式:
Array.prototype.unique =
Array.prototype.unique
|| function () {
return [...new Set(this)];
};
希望大家多多指教,不吝赐教~~