I'm trying to solve a simple challenge where I write a function that returns the first duplicate number in an array.
This is what I tried:
function duplicateNumber(arr) {
for (var i = 0; i < arr.length; i++) {
for (var j = arr.length; j >= 0; j--) {
if (arr[i] === arr[j]) {
var dup_num = arr[i]
}
}
}
return dup_num
}
It doesn't seem to be working. What am I doing wrong?
Just realized I'm also looping from end to beginning and beginning to end.
in the array = [3, 5, 6, 8, 5, 3]
the duplicate number should be 5
since it's duplicated before 3.
Your inner loop traverses down to
0
. Instead it should only go down toi+1
so that it doesn't run into the current character in the outer loop, making it think it found a duplicate.Also, your inner loop should start at
arr.length-1
to be correct so that it's not testing an out-of-bounds index.Code has been updated to reflect changes in the question
I also returned immediately when the duplicate was found, since
there's no reason to continuelooping should stop at that point so that you don't overwrite your result with a later duplicate.If no duplicate is found, it returns
undefined
.With the updated requirements, we store the index of the duplicated index, and continue on. If another duplicate is found it replaces the currently stored one.
The inner loop always starts at the index before the last found index, and traverses down to
i+1
, since we don't care about index above the last one found.