一、方法
方法一:先進(jìn)行原數(shù)組升序排序买决,然后對(duì)比相鄰元素
Array.prototype.distinct1 = function () {
console.time('distinct1'); //測(cè)試性能的相關(guān)代碼
var temp = this.sort(function (a, b) {
return a-b;
});
var res = [temp[0]];
for(var i=0; i<temp.length;i++){
if(temp[i] !== res[res.length-1]){
res.push(temp[i]);
}
}
console.timeEnd('distinct1');
console.log(res);
};
方法二:利用對(duì)象屬性唯一性
Array.prototype.distinct2 = function () {
console.time('distinct2'); //測(cè)試性能的相關(guān)代碼
var res=[],obj={};
for(var i=0; i<this.length;i++){
if(!obj[this[i]]){
res.push(this[i]);
obj[this[i]]=1;
}
}
console.timeEnd('distinct2');
console.log(res);
};
方法三:利用數(shù)組indexOf方法
Array.prototype.distinct3 = function () {
console.time('distinct3'); //測(cè)試性能的相關(guān)代碼
var res=[];
for(var i=0; i<this.length;i++){
if(res.indexOf(this[i])===-1){
res.push(this[i]);
}
}
console.timeEnd('distinct3');
console.log(res);
};
方法四:利用數(shù)組includes方法
Array.prototype.distinct4 = function () {
console.time('distinct4'); //測(cè)試性能的相關(guān)代碼
var res=[];
for(var i=0; i<this.length;i++){
if(!res.includes(this[i])){
res.push(this[i]);
}
}
console.timeEnd('distinct4');
console.log(res);
};
方法五:利用數(shù)組forEach限匣、includes方法
Array.prototype.distinct5 = function () {
console.time('distinct5'); //測(cè)試性能的相關(guān)代碼
var res=[];
this.forEach(function (value) {
if(!res.includes(value)){
res.push(value);
}
});
console.timeEnd('distinct5');
console.log(res);
};
方法六:利用ES6 Set方法
Array.prototype.distinct6 = function () {
console.time('distinct6'); //測(cè)試性能的相關(guān)代碼
let res = Array.from(new Set(this))
console.timeEnd('distinct6');
console.log(res);
};
二晓褪、性能
var data = [];
for(var j=0;j<1000000;j++){
data.push(Math.round(Math.random()*15));
}
data.distinct1(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ] 221ms
data.distinct2(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ] 5ms
data.distinct3(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ] 19ms
data.distinct4(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ] 20ms
data.distinct5(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ] 44ms
data.distinct6(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ] 77ms
三盟劫、總結(jié)
1饰迹、對(duì)比方法四、方法五醉锅,可知盡量少用forEach,而應(yīng)該用for循環(huán)代替。
2发绢、對(duì)比運(yùn)行時(shí)間硬耍,方法二所需時(shí)間最短,性能最優(yōu)边酒。
3经柴、有其他好的方法,歡迎大家在底下留言墩朦,我會(huì)補(bǔ)上去的坯认。