js去重

方法一:

Array.prototype.distinct = function() {
    var arr = this,
    result = [],
    len = arr.length;
    arr.forEach(function(value, index, arr) {
        var bool = arr.indexOf(value, index + 1);
        if (bool === -1) {
            result.push(value);
        }
    });
    return result;
}
var arr = [1, 1, 2, 3, 3, 3, 4, 2];
console.log(arr.distinct());  // [1, 3, 4, 2]

方法二:利用ES6的Set

function dedupe(arr) {
    return Array.from(new Set(arr));
}
console.log(dedupe(arr));  // [1, 2, 3, 4]

方法三:

function dedupe(arr) {
    return [...new Set(arr)];
}
console.log(dedupe(arr));  // [1, 2, 3, 4]

 

posted @ 2019-06-04 15:39  云深一梦,美梦成真  阅读(164)  评论(0编辑  收藏  举报