Question 3
Question
How would you implement a custom method to check if an array contains duplicates?
Answer
Explanation:
seen
Set: We create aSet
calledseen
. 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 theseen
set usingseen.has(item)
.If it is, we immediately return
true
because a duplicate has been found.
Adding to
seen
: If an item isn't already in theseen
set, 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