数组去重的七种方法

方法一

function fn0(ary) {
    for(var i=0;i

方法二

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

方法三

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

方法四

function fn3(ary) {
    let obj={};
    ary.forEach((item)=>{
        obj[item]=item;
    });
    ary=[];
    for (let key in obj){
        ary.push(obj[key])
    }
    return ary
};
console.log(fn3(ary));

方法五

function fn4(ary) {
    return ary.filter((item,index)=>{
        return !ary.slice(0,index).includes(item);
    })
};
console.log(fn4(ary));

方法六

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

方法七

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

你可能感兴趣的:(数组去重的七种方法)