-
indexof()
indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。如果要检索的字符串值没有出现,则该方法返回 -1
Array.prototype.unique = function () {
// 存放已遍历的满足条件的元素
var newArr = [];
for (var i = 0; i < this.length; i++) {
// indexOf()判断当前元素是否已存在
if (newArr.indexOf(this[i]) == -1) {
newArr.push(this[i]);
}
};
return newArr;
};
var a = [1, 2, 3, 4, 3, 1, 5, '1', null, false, 'false'];
var b = a.unique();
console.log(b); // [1, 2, 3, 4, 5, "1", null, false, "false"]
思想相同的indexOf()
Array.prototype.unique = function () {
// 创建一个新的临时数组,并且把当前数组的第一元素存入到数组中
var newArr = [];
// 从第二项开始遍历
for (var i = 1; i < this.length; i++) {
// 如果当前数组的第i项在当前数组中第一次出现的位置不是i,那么表示第i项是重复的,忽略掉,否则存入结果数组
if (this.indexOf(this[i]) == i) {
newArr.push(this[i]);
}
};
return newArr;
};
var arr2 = arr.unique();
console.log(arr); // [1, 2, 3, 4, 3, 1, 5, '1', null, false, 'false']
console.log(arr2); // [1, 2, 3, 4, 5, "1", null, false, "false"]
ES5
Array.prototype.unique = function() {
return this.filter((v, i) => this.indexOf(v) === i)
}
var a = [1, 2, 3, 4, 3, 1, 6, 8, 9, 5, 9, 2];
var b = a.unique();
console.log(b) // [1, 2, 3, 4, 6, 8, 9, 5]
ES6
Array.prototype.unique = function() {
return Array.from(new Set(this));
}
// 或
Array.prototype.unique = function() {
return [...new Set(this)];
}
var a = [1, 2, 3, 4, 3, 1, 6, 8, 9, 5, 9, 2];
var b = a.unique();
console.log(b) // [1, 2, 3, 4, 6, 8, 9, 5]
- hash
Array.prototype.unique = function() {
var json = {}, newArr = [];
for (!json[arr[i]]) {
newArr.push(arr[i]);
json[arr[i]] = true;
};
return newArr;
};
var a = [1, 2, 3, 4, 3, 1, 5];
var b = a.unique();
console.log(b) // [1, 2, 3, 4, 5]
但是这种会遇到一个问题?
比如[1, 2, 3, 4, 3, 1, 5, '1', null, false, 'false'],去重之后就变成了[1, 2, 3, 4, 5, null, false],这是为什么呢?在网上看大佬的总结!
其实我们在使用hash的时候就是把数组元素作为hash的key值,那么在使用的过程就会把数组元素变成了字符串,所以成了上面结果,再扩展一下,对于Boolean、null等都会有上面的情况,所以我们不能只关注数组元素的值,还要关注它的数据类型。
关于数据类型的判断,常见的typeof, instanceof。这里我推荐使用Object.prototype.toString.call。
完整如下:
Array.prototype.unique = function(){
var json = {}, newArr = [], len = this.length;
for(var i = 0; i < len; i++){
var temp = Object.prototype.toString.call(this[i]);
if(typeof json[this[i]] == "undefined"){
json[this[i]] = {};
json[this[i]][temp] = 1;
newArr.push(this[i]);
}else if(typeof json[this[i]][temp] == "undefined"){
json[this[i]][temp] = 1;
newArr.push(this[i]);
}else{
json[this[i]][temp]++;
}
}
console.log(json);
return newArr;
}
- 先排序,再去重
Array.prototype.unique = function() {
this.sort();
var newArr = [this[0]];
for (var i = 1; i < this.length; i++) {
if (this[i] !== newArr[newArr.length - 1]) {
newArr.push(this[i]);
}
}
return newArr;
}
var a = [1, 2, 3, 4, 3, 1, 6, 8, 9, 5, 9, 2];
var b = a.unique();
console.log(b) // [1, 2, 3, 4, 5, 6, 8, 9]