最简单循环查找去重
var array = [1, 1, '1'];
function unique(array) {
var res = [];
for (var i = 0, len = array.length; i < len; i++) {
var current = array[i];
if (res.indexOf(current) === -1) {
res.push(current)
}
}
return res;
}
console.log(unique(array));
如果该数组是有序我们还可以在这个函数中加一些东西
var array1 = [1, 2, '1', 2, 1];
var array2 = [1, 1, '1', 2, 2];
// 第一版
function unique(array, isSorted = false) { // 传入isSorted参数是否有序
var res = [];
var seen = [];
for (var i = 0, len = array.length; i < len; i++) {
var value = array[i];
if (isSorted) {
if (!i || seen !== value) {
res.push(value)
}
seen = value; // 如果数组是有序的我们可以判断相邻的值是否相等
}
else if (res.indexOf(value) === -1) {
res.push(value);
}
}
return res;
}
console.log(unique(array1)); // [1, 2, "1"]
console.log(unique(array2, true)); // [1, "1", 2]
es5的filter方法
// 不排序
var array = [1, 2, 1, 1, '1'];
function unique(array) {
var res = array.filter(function(item, index, array){
return array.indexOf(item) === index; // indexOf只返回第一次找到该值的位置, 因此之后出现的都会返回false, 过滤掉
})
return res;
}
console.log(unique(array));
// 排序
var array = [1, 2, 1, 1, '1'];
function unique(array) {
return array.concat().sort().filter(function(item, index, array){ // concat目的返回一个新的数组
return !index || item !== array[index - 1] // !index目的: 不计算第一项
})
}
console.log(unique(array));
Object键值对去重
此方法去重的最干净
var array = [{value: 1}, {value: 1}, {value: 2}];
function unique(array) {
var obj = {};
return array.filter(function(item, index, array){
console.log(typeof item + JSON.stringify(item)) // typeof目的: 为了防止1和'1', 这种被类型转换, 造成丢失
// JSON.string目的: 为了防止对象出现这种情况"object[object Object]", 所以使用了这个函数先转换成字符串, 不调用toSting
return obj.hasOwnProperty(typeof item + JSON.stringify(item)) ? false : (obj[typeof item + JSON.stringify(item)] = true)
})
}
console.log(unique(array)); // [{value: 1}, {value: 2}]
es6的set去重方法
ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。
向 Set 加入值的时候,不会发生类型转换,所以5和”5”是两个不同的值。Set 内部判断两个值是否不同,使用的算法叫做“Same-value-zero equality”,它类似于精确相等运算符(===),主要的区别是NaN等于自身,而精确相等运算符认为NaN不等于自身。
var array = [1, 2, 1, 1, '1'];
function unique(array) {
return Array.from(new Set(array));
}
console.log(unique(array)); // [1, 2, "1"]
或者也可以这样写
function unique(array) {
return [...new Set(array)];
}