skip to Main Content

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


  1. 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
    }
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search