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;
}
Edit :
found better way to visualize the if statement with,
if (existingNumbers.includes(array[i])) {
return true;
} else {
existingNumbers.push(array[i]);
}
though .includes method seems to have O(n) from https://stackoverflow.com/a/48761894/20581562
so previous one should be better?, at least it helped me visualize the code