Home >Web Front-end >JS Tutorial >JavaScript remove duplicate elements from array

JavaScript remove duplicate elements from array

大家讲道理
大家讲道理Original
2016-11-10 13:15:451385browse

Title: Remove duplicate elements from the array [4,3,"3",3,5,7,5] and return [4,3,"3",5,7]

(function() {
    'use strict';
    function filter1(arr) {
        var b = [];
        arr.forEach(function(i) {
            if (b.indexOf(i) == -1) {
                b.push(i);
            }
        });
        return b;
    }
 
    function filter2(arr) {
        var b = {}, c = [];
        arr.forEach(function(i) {
            b[i] = b[i] ? b[i] : {};
            var type = typeof i;
            if (!b[i][type]) {
                b[i][type] = true;
                c.push(i);
            }
        });
        return c;
    }
 
    function timer(fn, arr) {
        console.time('filter');
        fn.call(this, arr);
        console.timeEnd('filter');
    }
 
    function testArr(n) {
        // var arr = [4,3,"3",3,5,7,5];
        var arr = [];
        for (var i = 0; i < n; i++) {
            arr.push(i);
            arr.push(i + "");
        }
        return arr;
    }
 
    for (var i = 1; i <= 100; i++) {
        console.log(i * 10);
        var arr = testArr(i * 10);
        timer(filter1, arr);
        timer(filter2, arr);
    }
})();


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn