DEV Community

Avnish
Avnish

Posted on

In Javascript, how do I check if an array has duplicate values

You can check for duplicate values in an array using various methods in JavaScript. Here's a common approach using a hash table (an object in JavaScript) to keep track of the occurrences of each element:

function hasDuplicates(array) {
    const seen = {}; // Create an empty object to store seen elements
    for (let i = 0; i < array.length; i++) {
        if (seen[array[i]]) { // If the element is already in the object, return true
            return true;
        }
        seen[array[i]] = true; // Otherwise, mark the element as seen
    }
    return false; // If no duplicates found, return false
}

// Example usage:
console.log(hasDuplicates([1, 2, 3, 4, 5])); // Output: false
console.log(hasDuplicates([1, 2, 3, 4, 1])); // Output: true
console.log(hasDuplicates(['a', 'b', 'c', 'd', 'a'])); // Output: true
console.log(hasDuplicates([1, 1, 1, 1, 1])); // Output: true
console.log(hasDuplicates([1, 2, 3, 4, 5, 5])); // Output: true
Enter fullscreen mode Exit fullscreen mode

Let's break down the code step by step:

  1. hasDuplicates is a function that takes an array as an argument.
  2. Inside the function, we initialize an empty object called seen to keep track of the elements we've encountered.
  3. We loop through each element of the array using a for loop.
  4. For each element, we check if it exists in the seen object. If it does, it means it's a duplicate, so we return true.
  5. If the element is not found in the seen object, we mark it as seen by setting its value in the object to true.
  6. If we finish the loop without finding any duplicates, we return false.
  7. We provide 5 examples of using this function with different arrays, each demonstrating different scenarios of having duplicates or not.

The output is also provided in comments next to each example usage.

Demo

Top comments (0)