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: trueExplanation:
seenSet: We create aSetcalledseen. Sets only store unique values, so they are perfect for checking duplicates.Iteration: The code iterates through each item in the input array
arr.Duplicate Check:
For every
item, we check if it's already present in theseenset usingseen.has(item).If it is, we immediately return
truebecause a duplicate has been found.
Adding to
seen: If an item isn't already in theseenset, we add it usingseen.add(item)to keep track of encountered values.No Duplicates: If the loop completes without finding any duplicates, the function returns
false.
Last updated