Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

后端 未结 30 3167
再見小時候
再見小時候 2020-11-21 04:35

I need to check a JavaScript array to see if there are any duplicate values. What\'s the easiest way to do this? I just need to find what the duplicated values are - I don\'

30条回答
  •  别跟我提以往
    2020-11-21 05:11

    You can add this function, or tweak it and add it to Javascript's Array prototype:

    Array.prototype.unique = function () {
        var r = new Array();
        o:for(var i = 0, n = this.length; i < n; i++)
        {
            for(var x = 0, y = r.length; x < y; x++)
            {
                if(r[x]==this[i])
                {
                    alert('this is a DUPE!');
                    continue o;
                }
            }
            r[r.length] = this[i];
        }
        return r;
    }
    
    var arr = [1,2,2,3,3,4,5,6,2,3,7,8,5,9];
    var unique = arr.unique();
    alert(unique);
    

提交回复
热议问题