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

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

    ES6 offers the Set data structure which is basically an array that doesn't accept duplicates. With the Set data structure, there's a very easy way to find duplicates in an array (using only one loop).

    Here's my code

    function findDuplicate(arr) {
    var set = new Set();
    var duplicates = new Set();
      for (let i = 0; i< arr.length; i++) {
         var size = set.size;
         set.add(arr[i]);
         if (set.size === size) {
             duplicates.add(arr[i]);
         }
      }
     return duplicates;
    }
    

提交回复
热议问题