/**
* 方法一
* 把数组元素逐个添加到另一个数组,添加前检查这个元素是否有重复,如果有就直接丢掉
* 循环嵌套,效率低
* indexOf 会遍历数组,消耗较多时间
* @returns {Array}
*/
Array.prototype.unique1 = function () {
var result = []; //一个新的临时数组
for (var i = 0; i < this.length; i++) { //遍历当前数组
//如果当前数组的第i已经保存进了临时数组,那么跳过,
//否则把当前项push到临时数组里面
if (result.indexOf(this[i]) == -1) {
result.push(this[i]);
}
}
return result;
};
var arr = [5, 4, 6, 2, 10, 1, 6];
var arrSorted = arr.unique1();
// console.log(arr); //[5, 4, 6, 2, 10, 1, 6]
// console.log(arrSorted); //[5, 4, 6, 2, 10, 1]
/**
* 方法二
* 用一个对象记录已有的元素为true,这样就可以避免内层循环。
* 对象的下标引用会较快
* @returns {Array}
*/
Array.prototype.unique2 = function () {
var result = [], hash = {}; //result为临时数组,hash为存储对象
for (var i = 0; i < this.length; i++) { //遍历当前数组
if (!hash[this[i]]) { //如果对象中没有当前项
hash[this[i]] = true; //存入对象
result.push(this[i]); //把当前项push到临时数组里面
}
}
return result;
};
var arr2 = [5, 4, 6, 22, 10, 2, 1, 6];
var arrSorted2 = arr2.unique2();
//console.log(arr2); //[5, 4, 6, 22, 10, 2, 1, 6]
//console.log(arrSorted2); //[5, 4, 6, 22, 10, 2, 1]
/**
* 方法三
* indexOf 会遍历数组,消耗较多时间
* @returns {*[]}
*/
Array.prototype.unique3 = function () {
var result = [this[0]]; //结果数组
for (var i = 1; i < this.length; i++) { //从第二项开始遍历
//如果当前数组的第i项在当前数组中第一次出现的位置不是i,
//那么表示第i项是重复的,忽略掉。否则存入结果数组
if (this.indexOf(this[i]) == i) {
result.push(this[i]);
}
}
return result;
};
var arr3 = [5, 4, 6, 33, 10, 3, 1, 6];
var arrSorted3 = arr3.unique3();
//console.log(arr3); //[5, 4, 6, 33, 10, 3, 1, 6]
//console.log(arrSorted3); //[5, 4, 6, 33, 10, 3, 1]
/**
* 方法四
* @returns {*[]}
*/
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;
};
var arr4 = [5, 4, 6, 444, 10, 44, 1, 6];
var arrSorted4 = arr4.unique4();
console.log(arr4); //[1, 10, 4, 44, 444, 5, 6, 6]
console.log(arrSorted4); //[1, 10, 4, 44, 444, 5, 6]
来源: http://blog.csdn.net/chengxuyuan20100425/article/details/8497277