4

JavaScript数组去重方法的总结

前言

在JavaScript中数组是比较常用的,本文中总结了下数组去重的几种常用方法,如有问题,请指正。

简单粗暴的一种,ES6中set方法:
var arr = [1,2,2,3,3,4,5,5];
console.log([...new Set(arr)])  //[1, 2, 3, 4, 5]
遍历数组,建立新数组,利用indexOf()判断是否存在于新数组中,不存在则push到新数组,最后返回新数组:
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;
}
var arr1 = [1,2,2,2,3,3,4,4,5,5];
console.log(removeSame(arr1))  //[1, 2, 3, 4, 5]
遍历数组,利用object对象保存数组值,判断数组值是否已经保存在object中,未保存则push到新数组并用object[arrayItem]=1的方式记录保存:
function removeSame(arr){
    var temp = {},ret = [];
    for (var i = 0,j=arr.length;i<j;i++){
        debugger;
        if(!temp[arr[i]]){
            temp[arr[i]] = 1;
            ret.push(arr[i])
        }
    }
    return ret;
}
var arr2 = [1,2,2,2,3,3,4,4,5];
console.log(removeSame(arr2))   //[1, 2, 3, 4, 5]
根据数组下标判断法, 遍历数组,利用indexOf()判断元素的值是否与当前索引相等,如相等则加入
function removeSame(arr){
    var ret = [];
    arr.forEach(function(ele,index){
        if(arr.indexOf(ele) === index){
            ret.push(ele)
        }
    })
    return ret;
}
var arr3 = ["apple","apple","orange","orange","banana"]
console.log(removeSame(arr3))    //["apple", "orange", "banana"]
数组先进行排序,然后比较原数组与新数组,一头一尾进行去重:
function deleteSame(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;
}
var arr4 = ["apple","apple","orange","orange","banana"];
console.log(deleteSame(arr4)) //["apple", "banana", "orange"]
利用filter()方法循环对数组中的元素调用callback函数, 如果返回true 保留,如果返回false 过滤掉, 返回新数组,老数组不变
var arr_unique = ["apple","apple","orange","orange","banana"].filter(function(element,index,array){
    return array.indexOf(element) === index;
})
console.log(arr_unique) //["apple", "orange", "banana"]

简单的总结了6种方法,如有不足请指正,可以继续补充,大家共同学习。


sunshine1213
89 声望3 粉丝

冷眼看世界