前端JS数组去重的7种方式

web前端还是java开发 java怎么实现前端开发 前端开发和java开发的区别

javascript 代码

## 1.indexOf push

var ary =[1,2,1,3,4,5,2];
var ary1=[];
for(var i=0;i<ary.length;i++){
if(ary1.indexOf(ary[i])===-1){
ary1.push(ary[i]);
}
}
console.log(ary1)

## 2.新增的属性名会被保存

var ary =[1,2,3,13,4,5,2];
var obj={};//
for(var i=0;i<ary.length;i++){
var cur=ary[i];
if(obj[cur]==cur){
ary[i]=ary[ary.length-1];
ary.length–;
i–;
continue;
}obj[cur]=cur;
}

console.log(ary)

## 3、双循环

let ary=[1,1,2,2,3,4,4,4,5];
function f1(ary) {
for(var i=0;i<ary.length;i++){
for(var j=0;j<i;j++){
if(ary[i]==ary[j]){
ary.splice(i,1);
i–;
}
}
}
return ary;
}

## 4、 indexOf!==lastIndexOf

function fn1(ary) {
ary.map((item,index)=>{
if(ary.indexOf(item)!==ary.lastIndexOf(item)){
ary.splice(index,1)
}
});
return ary;
};
console.log(fn1(ary));

##/5、filter indexOf

var ary=[6,5,5,5,5,3,3,2,1,4,2,1];
function quChong(ary) {
 return ary.filter((item,index)=>{
     return ary.indexOf(item)===index
   })
}
console.log(quChong(ary));
##6、fileter includes

function fn1(ary) {
return ary.filter((item,index)=>{
return !ary.substr(0,index).includes(item)
})
}
console.log(fn1(

## 7、new Set()

function fn1(ary) {
return […new Set(ary)]
}
console.log(fn1(ary));

 

function fn1(ary) {
return Array.from(new Set(ary))
}
console.log(fn1(ary));

java前端开发教程pdf 前端开发java哪个好学 秦皇岛前端开发java培训机构

» 本文来自:前端开发者 » 《前端JS数组去重的7种方式》
» 本文链接地址:https://www.rokub.com/5690.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!