-1

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

me-an-ape
  • 57
  • 1
  • 5
  • *"`if (existingNumbers[array[i]] === undefined)`"* means "if the number you're checking for has _not_ been encountered before." In that case, you set it to `1`. *`else`*, in case you _did_ encounter the number before, you `return true`. It seems fairly straight forward…? – deceze May 04 '23 at 07:19

2 Answers2

2

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

else if (existingNumbers[array[i]] !== undefined) {
    return true
}
yagil
  • 55
  • 1
  • 7
1

Try this,

const foo = [1, 2, 3, 4];
const bar = [1, 2, 3, 1];

function isUniqueArray(arr) {
  for (var i = 0; i < arr.length; i++) {
    let itemCount = arr.filter((item) => item == arr[i]).length;
    if (itemCount > 1) {
      return false;
    }
  }
  return true;
}


console.log(isUniqueArray(foo));
console.log(isUniqueArray(bar));

https://codepen.io/emretnrvrd/pen/dygZgda