##数组中值为number,string,boolean时:
var data=[1,2,3,2,5,1];
1.ES6 Set
function unique(arr){
let newArr=new Set(data);
let result=[...newArr];
return result;
}
console.log(unique(data));//[1, 2, 3, 5]
2.两层for
function unique(arr){
var re = [array[0]];
for (var i = 1; i < array.length; i++) {
var isunique = true;
for (var r = 0; r < re.length; r++) {
if (re[r] === array[i]) {
isunique = false;
}
}
if (isunique) {
re.push(array[i]);
}
}
return re;
}
console.log(unique(data));//[1, 2, 3, 5]
3.利用对象属性是否存在
function unique(arr){
var re = [];
var obj={};
for (var i = 0; i < arr.length; i++) {
if(!obj.hasOwnProperty(arr[i])){
re.push(arr[i]);
obj[arr[i]]=true;
}
}
return re;
}
console.log(unique(data));//[1, 2, 3, 5]
##数组中值为对象时,并且两个属性结合判断,如下:name和age都相等时,判断为重复:
var data = [{name: "a", age: 20, count: 5},
{name: "b", age: 21, count: 8},
{name: "a", age: 20, count: 9}
];
1.对象属性
var result = [];
var obj = {};
for(var i =0; i<arr.length; i++){
if(!obj[arr[i][name1]+"|"+arr[i][name2]]){
result.push(arr[i]);
obj[arr[i][name1]+"|"+arr[i][name2]] = true;
}
}
return result;
2.双for
var re = [array[0]];
for (var i = 1; i < array.length; i++) {
var isunique = true;
for (var r = 0; r < re.length; r++) {
if (re[r].name === array[i].name&&re[r].age === array[i].age) {
isunique = false;
}
}
if (isunique) {
re.push(array[i]);
}
}
return re;
3.reduce
function arrayUnique2(arr, name1,name2) {
var obj = {};
return arr.reduce(function (item, next) {
if(!obj[arr[i][name1]+"|"+arr[i][name2]]){
item.push(arr[i]);
obj[arr[i][name1]+"|"+arr[i][name2]] = true;
}
return item;
}, []);
}
console.log(arrayUnique2(data, "name","age"));