数组去重

测试用例:

var array = [1, 1, '1', '1', null, null, 
                undefined, undefined, 
                new String('1'), new String('1'), 
                /a/, /a/,
                NaN, NaN
            ];

一、使用Set:

let unique_1 = arr => [...new Set(arr)];

输出结果:

>  Array(9) [ 1, "1", null, undefined, String, String, /a/, /a/, NaN ]

二、使用fliter

function unique_2(array) {
    var res = array.filter(function (item, index, array) {
        // 返回满足 当前元素在原始数组中的第一个索引 === 当前索引值 的元素
        return array.indexOf(item,0) === index;
    })
    return res;
}

输出结果:

Array(8) [ 1, "1", null, undefined, String, String, /a/, /a/ ]

三、使用Object键值对
去重效果最好

function unique_3(array) {
    var obj = {};
    return array.filter(function (item, index, array) {
    // 使用obj[typeof item + item] = true,原因就在于对象的键值只能是字符串,所以使用typeof item + item代替
        return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)
    })
}

输出结果:

> Array(7) [ 1, "1", null, undefined, String, /a/, NaN ]
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务