Coding Challenge - #3: Find Duplicate Values

Write a function findDuplicates(arr) that returns an array of values that appear more than once in the input array, each value listed only once, in the order they first repeat. For example, findDuplicates([1,2,3,2,4,1]) should return [2,1].

function findDuplicates(arr) {
  // your code here
}

Rules:

  • Plain JavaScript only, no libraries
  • Return values in order of first repeat, not first appearance
  • Each duplicate value should appear only once in the result
  • Solution should be about 3 to 10 lines

Post your solution as a reply. Answer goes up in about a day.

Here is my attempt:

function findDuplicates(arr) {
   let unique = new Set();
   let duplicates = new Set();
   for (let i = 0; i < arr.length; i++) {
         let current = arr[i];
         if (!unique.has(current)) {
              unique.add(current);
         } else {
              duplicates.add(current);
         }
   }
   return duplicates;
}

console.log(findDuplicates([1,2,3,2,4,1]));

Logged it, no verdict from me though. Answer drops later today, try not to stare at that return type too hard until then.

Your logic is solid-you’re tracking unique and duplicate values correctly.

The challenge asks for an array though, not a Set.

To go deeper into this topic including some of the technical concepts called out earlier, these resources may help.

Ok - now it returns an array!

function findDuplicates(arr) {
   let unique = new Set();
   let duplicates = new Set();
   
   for (let i = 0; i < arr.length; i++) {
         let current = arr[i];
         if (!unique.has(current)) {
              unique.add(current);
         } else {
              duplicates.add(current);
         }
   }
   
   // Convert the Set to an Array before returning
   return [...duplicates];
}

console.log(findDuplicates([1, 2, 3, 2, 4, 1]));

sets and spread, love it, tucked that guess away for later. answer drops later today so we’ll see how it holds up