数组去重总结

Author Avatar
Yoler|雷永亮 6月 15, 2017

方法一

使用filter高阶函数

    let arr = [12,12,14,15,12,13,1,3,14,1,5,1,6]
    let brr = arr.filter((item, index, arr) => {
        if (arr.indexOf(item) == index) {
            return true
        }
    })

    console.log(brr)  //[ 12, 14, 15, 13, 1, 3, 5, 6 ]

方法二

使用对象的键唯一原理

    let dic = {}
    let newarr = []
    arr.forEach((item, index) => {
        if (!dic[item]) {
            dic[item] = 1
            newarr.push(item)
        }
    })

    console.log(brr)  //[ 12, 14, 15, 13, 1, 3, 5, 6 ]

方法三

使用es6 Set对象

    let arr = [12,12,14,15,12,13,1,3,14,1,5,1,6]
    let sarr = new Set(arr)

    console.log(sarr)   //Set { 12, 14, 15, 13, 1, 3, 5, 6 }