3

数组去重的方式有很多种,现总结一些备以后查漏补缺来用。

对基本数组类型去重:

(1)set 和 array.from()实现

var str,
    strs = ['a', 'b', 'c', 'er', 'd', 'er', 'a', 'b', 'c'];

function removeRepeat(arr) {
   return  Array.from(new Set(arr))
}
console.log(removeRepeat(strs)) //["a", "b", "c", "er", "d"]

(2) indexOf和forEach()

var str=[],
    strs = ['a', 'b', 'c', 'er', 'd', 'er', 'a', 'b', 'c'];

function removeRepeat() {
  strs.forEach(v=>{
    if(str.indexOf(v) < 0) str.push(v)
  })
  console.log(str) //["a", "b", "c", "er", "d"]
}

(3)map 和 filter

var str=[],
    strs = ['a', 'b', 'c', 'er', 'd', 'er', 'a', 'b', 'c'];
function removeRepeat(arr) {
  const unique = new Map()
  return arr.filter(v=>{
    return !unique.has(v) && unique.set(v,1)
  })
}
 console.log(removeRepeat(strs)) //["a", "b", "c", "er", "d"]

延伸1:需要对数组排序去重

var str=[],
    strs = ['a', 'b', 'c', 'er', 'd', 'er', 'a', 'b', 'c'];

function removeRepeat(arr) {
 let arry = arr.sort()
 return arr.sort().filter((v,index) => {
   return !index || v !== arry[index-1]
 })
}
console.log(removeRepeat(strs))//  ["a", "b", "c", "d", "er"]

延伸2:某一个元素只出现一次


(1)利用filter,indexof,lastIndexOf对基本类型数组去重复元素

var str,
    strs = ['a', 'b', 'c', 'er', 'd', 'er', 'a', 'b', 'c'];

function removeRepeat() {
    str = strs.filter(function (value, index, array) {
        return array.indexOf(value) === array.lastIndexOf(value);
    })
    console.log(str) //["d"]
}

(2)利用lastIndexOf,splice对基本类型数组去重复元素

var str,
    strs = ['a', 'b', 'c', 'er', 'd', 'er', 'a', 'b', 'c'];

function removeRepeat() {
    for (var i = 0; i < strs.length; i++) {
        if (i !== strs.lastIndexOf(strs[i])) strs.splice(i, 1);
    }
    console.log(str) //["d"]
}

(1)和(2)的方法大同小异,原理是一样

延伸3:对数组对象进行去重

var Messages = [
    {
        "timestamp": 1474328370007,
        "message": "hello"
    },
    {
        "timestamp": 1474328302520,
        "message": "how are you"
    },
    {
        "timestamp": 1474328370007,
        "message": "hello"
    },
    {
        "timestamp": 1474328370007,
        "message": "hello"
    }
]

var NoRepeatMessages = [];

function RemoveRepeat(arr) {
    var hashFlag = {}
    arr.forEach((v,index) => {
        if (!hashFlag[v.timestamp]) {
            hashFlag[v.timestamp] = true;
            NoRepeatMessages.push(v);
        }
    });
  console.log(NoRepeatMessages) //[{"timestamp": 1474328370007,"message": "hello"},{ "timestamp": 1474328302520,"message": "how are you"}]
}
RemoveRepeat(Messages)

kouxiangxinfu
5 声望0 粉丝