#数组去重方法
var a = [1111,1112,1113,1111122,1113,1112,1113,1114,511,611,711,833,933,711,833,933,330];
输出 [1111, 1112, 1113, 1111122, 1114, 511, 611, 711, 833, 933, 330];
(N为循环执行次数,T为所消耗时间)
1.使用Set + Array
function uniqueArray(arr){
return Array.from(new Set(arr));
}
对于N = 100/1000/10000 T = 124ms/650ms/5508ms
2.使用splice
function uniqueArray(arr){
for(var i = 0; i < arr.length - 1; i++){
for(var j = i + 1; j < arr.length; j++){
if(arr[j] === arr[i]){
arr.splice(j--, 1);
}
}
}
return arr;
}
对于N = 100/1000/10000 T = 116ms/594ms/5079ms
3.只用Array
function uniqueArray(arr){
var retArray = [];
for(var i = 0; i < arr.length; i++){
if(retArray.indexOf(arr[i]) < 0){
retArray.push(arr[i]);
}
}
return retArray;
}
对于N = 100/1000/10000 T = 103ms/613ms/4894ms
4.先排序
function uniqueArray(a) {
a.sort();
var res = [a[0]];
for(var i = 1; i < a.length; i++){
if(a[i] !== res[res.length - 1]){
res.push(a[i]);
}
}
return res;
}
对于N = 100/1000/10000 T = 119ms/794ms/5100ms
5.利用json(推荐)
function uniqueArray(a) {
var hash = {},result = [];
for (var i = 0; i < a.length; i++){
if (!hash[a[i]]){
hash[a[i]] = true;
result.push(a[i]);
}
}
return result;
}
对于N = 100/1000/10000 T = 105ms/586ms/5112ms
##測試時間
var start = new Date().getTime();
var a = [1111,1112,1113,1111122,1113,1112,1113,1114,511,611,711,833,933,711,833,933,330];
function uniqueArray(arr){
return Array.from(new Set(arr));
}
for (var i = 0; i < 10000; i++) {
uniqueArray(a)
console.log(uniqueArray(a))
}
var end = new Date().getTime();
console.log(end - start);
document.write(end - start)