Question 3

Question

How would you implement a custom method to check if an array contains duplicates?

Answer

function hasDuplicates(arr) {
  const seen = new Set(); 

  for (const item of arr) {
    if (seen.has(item)) {
      return true; // Duplicate found!
    }
    seen.add(item);
  }

  return false; // No duplicates found
}

// Example usage:
const array1 = [1, 2, 3, 4, 5];
console.log(hasDuplicates(array1)); // Output: false

const array2 = [1, 2, 3, 2, 4];
console.log(hasDuplicates(array2)); // Output: true

Explanation:

  1. seen Set: We create a Set called seen. Sets only store unique values, so they are perfect for checking duplicates.

  2. Iteration: The code iterates through each item in the input array arr.

  3. Duplicate Check:

    • For every item, we check if it's already present in the seen set using seen.has(item).

    • If it is, we immediately return true because a duplicate has been found.

  4. Adding to seen: If an item isn't already in the seen set, we add it using seen.add(item) to keep track of encountered values.

  5. No Duplicates: If the loop completes without finding any duplicates, the function returns false.

Last updated