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

后端 未结 30 3149
再見小時候
再見小時候 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:35

    This is probably one of the fastest way to remove permanently the duplicates from an array 10x times faster than the most functions here.& 78x faster in safari

    function toUnique(a,b,c){//array,placeholder,placeholder
     b=a.length;
     while(c=--b)while(c--)a[b]!==a[c]||a.splice(c,1)
    }
    var array=[1,2,3,4,5,6,7,8,9,0,1,2,1];
    toUnique(array);
    console.log(array);
    
    1. Test: http://jsperf.com/wgu
    2. Demo: http://jsfiddle.net/46S7g/
    3. More: https://stackoverflow.com/a/25082874/2450730

    if you can't read the code above ask, read a javascript book or here are some explainations about shorter code. https://stackoverflow.com/a/21353032/2450730

    EDIT As stated in the comments this function does return an array with uniques, the question however asks to find the duplicates. in that case a simple modification to this function allows to push the duplicates into an array, then using the previous function toUnique removes the duplicates of the duplicates.

    function theDuplicates(a,b,c,d){//array,placeholder,placeholder
     b=a.length,d=[];
     while(c=--b)while(c--)a[b]!==a[c]||d.push(a.splice(c,1))
    }
    var array=[1,2,3,4,5,6,7,8,9,0,1,2,1];
    
    toUnique(theDuplicates(array));
    

提交回复
热议问题