数组去重的几种方法

1、双层循环:

优点:兼容性最好

function unique(arr){
    var newarr = [];
    for(var i = 0,aLen = arr.length; i

2、标记

function oSort(arr) {
    var result = {};
    var newArr = [];
    for (var i = 0; i < arr.length; i++) {
        if (!result[arr[i]]) {   //  !undefined为true
            newArr.push(arr[i])
            result[arr[i]] = 1
        }
    }
    return newArr
}

使用indexOf

var array = [1, 1, '1'];

function unique(array) {
    var res = [];
    for (var i = 0, len = array.length; i < len; i++) {
        var current = array[i];
        if (res.indexOf(current) === -1) {
            res.push(current)
        }
    }
    return res;
}

console.log(unique(array));

使用filter

var array = [1, 2, 1, 1, '1'];

function unique(array) {
    var res = array.filter(function(item, index, array){
        return array.indexOf(item) === index;
    })
    return res;
}

console.log(unique(array));

es6 Set

var array = [1, 2, 1, 1, '1'];

function unique(array) {
   return Array.from(new Set(array));
  //return [...new Set(array)]
}

console.log(unique(array)); // [1, 2, "1"]

es6 Map

function unique (arr) {
    const seen = new Map()
    return arr.filter((a) => !seen.has(a) && seen.set(a, 1))
}

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