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

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

    Following logic will be easier and faster

    // @Param:data:Array that is the source 
    // @Return : Array that have the duplicate entries
    findDuplicates(data: Array): Array {
            return Array.from(new Set(data)).filter((value) => data.indexOf(value) !== data.lastIndexOf(value));
          }
    

    Advantages :

    1. Single line :-P
    2. All inbuilt data structure helping in improving the efficiency
    3. Faster

    Description of Logic :

    1. Converting to set to remove all duplicates
    2. Iterating through the set values
    3. With each set value check in the source array for the condition "values first index is not equal to the last index" == > Then inferred as duplicate else it is 'unique'

    Note: map() and filter() methods are efficient and faster.

提交回复
热议问题