数组去重

爱宜淡写Vivan
一.ES6中set方法:[...new Set(arr)]
var arr1 = [1,2,2,3,3,4,5,5];
[...new Set(arr1)].toString()
二.遍历数组,建立新数组,利用indexOf()判断是否存在于新数组中,不存在则push到新数组,最后返回新数组
var arr2 = [1,2,2,2,3,3,4,4,5,5];
function removeSame(arr){
    var ret = [];
    for(var i=0,j=arr.length;i<j; i++){
        if(ret.indexOf(arr[i]) === -1){
            ret.push(arr[i])
        }
    }
    return ret;
}
三.遍历数组,利用object对象保存数组值,判断数组值是否已经保存在object中,未保存则push到新数组并用object[arrayItem]=1的方式记录保存
var arr3 = [1,2,2,2,3,3,4,4,5]
function removeSame(arr){
    var temp = {},ret = [];
    for (var i = 0,j=arr.length;i<j;i++){
        //debugger;
        console.log(temp[arr[i]]);
        if(!temp[arr[i]]){
            temp[arr[i]] = 1;
            ret.push(arr[i])
        }
    }
    return ret;
}
四.根据数组下标判断法, 遍历数组,利用indexOf()判断元素的值是否与当前索引相等,如相等则加入
var arr4 = ["apple","apple","orange","orange","banana"]
function removeSame(arr){
    var ret = [];
    arr.forEach(function(ele,index){
        if(arr.indexOf(ele) == index){
            ret.push(ele)
        }
    })
    return ret;
}
五.数组先进行排序,然后比较原数组与新数组,一头一尾进行去重
var arr5 = ["apple","apple","orange","orange","banana"]
function removeSame(arr){
    var ret = [],end;
    debugger;
    arr.sort();   // ["apple","apple","banana","orange","orange",];
    end = arr[0];
    ret.push(arr[0]);
    for(var i = 1; i<arr.length; i++){
        if(arr[i] != end){
            ret.push(arr[i]);
            end = arr[i];
        }
    }
    return ret;
}
阅读 270
26 声望
0 粉丝
0 条评论
26 声望
0 粉丝
宣传栏