i have this code that check for duplicates
function hasDuplicateValue(array) {
var existingNumbers = [];
for (var i = 0; i < array.length; i++) {
if (existingNumbers[array[i]] === undefined) {
existingNumbers[array[i]] = 1;
} else {
return true;
}
}
return false;
}
the variable existingNumbers is to ‘mark’ the values in array and will set to 1 if have found any value in array but will immediately returns true if it have seen that value before.
every value of existingNumbers[array[i]] will return to undefined then existingNumbers will ‘mark’ it so it changes to 1.
i don’t know when the code checks for duplicates, i just know that existingNumbers will have all value that goes from undefined to 1. because say if i change the else to
else if (existingNumbers[array[i]] !== undefined) {
return true
}
every item on existingNumbers is 1 right? so it will always returns true?
i think i just need to know the condition that happens in ‘xxx’ below
else (xxx) {
return true;
}
2
Answers
The function works because it uses an array to keep track of the numbers that have already been seen. When it encounters a new number, it checks whether that number already exists in the array or not. If it doesn’t exist, the function adds the number to the array. If it does exist, the function knows that the input array contains a duplicate value and immediately returns true.
This part of code checks if a value is in the array
Try this,
https://codepen.io/emretnrvrd/pen/dygZgda