- indexof()方法
function unique(array){
var newArra=[];
for (var i =0;i<array.length;i++){
if(newArra.indexOf(array[i])===-1){
newArra.push(array[i]);
}
}
return newArra;
}
var array =[2,2,21,3,5,21];
var a = unique(array);
console.log(a);
- sort()方法(排序后去重)
function unique(array){
array = array.sort(); //排序
var newArra =[array[0]];
for(var i =1;i<array.length;i++){
if(array[i]!==array[i-1]){
newArra.push(array[i]);
}
}
return newArra;
}
var array =[2,2,21,3,5,21];
var a = unique(array);
console.log(a);
3.两个for嵌套去重(优化遍历)
function unique(array){
for(var i =0;i<array.length;i++){
for(var j=i+1;j<array.length;j++){
if(array[j]===array[i]){
array.splice(j,1);
}
}
}
return array;
}
var array =[2,2,21,3,5,21];
var a = unique(array);
console.log(a);
- Map方法
function unique(array) {
var map = new Map();
var newArray = [];
for (var i = 0; i<array.length; i++) {
if(!map .has(array[i])){ // 如果没有该key值
map .set(array[i]);
newArray.push(array[i]);
}
}
return newArray;
}
var array =[2,2,21,3,5,21];
var a = unique(array);
console.log(a);
5.reduce+includes
function unique(array) {
return array.reduce((pre,cur)=>{
return pre.includes(cur) ? pre : [...pre,cur];
},[]);
}
var array =[2,2,21,3,5,21];
var a = unique(array);
console.log(a);
- es6常用 set方法
var newArray=[...new Set(arr)]
网友评论