首页 > 技术文章 > js 实现去重

cap-rq 2019-10-31 15:36 原文

 

ES6 set去重

Array.from(new Set([1,2,3,3,4,4]))    // [1,2,3,4]

[...new Set([1,2,3,3,4,4])]        // [1,2,3,4]

 

使用 for of 去重(On)

Array.prototype.distinct = function() {
    const map = {}
    const result = []
    for (const n of this) {
        if (!(n in map)) {
            map[n] = 1
            result.push(n)
        }
    }
    return result
}
[1,2,3,3,4,4].distinct(); //[1,2,3,4]

 

推荐阅读