DEV Community

Avnish
Avnish

Posted on

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

You can check if an array has duplicate values in JavaScript by iterating through the array and keeping track of seen elements in a separate data structure, such as an object or a Set. Here's how you can do it:

Using an Object:

function hasDuplicates(array) {
    var seen = {};
    for (var i = 0; i < array.length; i++) {
        if (seen[array[i]]) {
            return true;
        } else {
            seen[array[i]] = true;
        }
    }
    return false;
}

var arr = [1, 2, 3, 4, 5, 6];
console.log(hasDuplicates(arr)); // Output: false

var arrWithDuplicates = [1, 2, 3, 4, 4, 5];
console.log(hasDuplicates(arrWithDuplicates)); // Output: true
Enter fullscreen mode Exit fullscreen mode

Using a Set:

function hasDuplicates(array) {
    var set = new Set();
    for (var i = 0; i < array.length; i++) {
        if (set.has(array[i])) {
            return true;
        } else {
            set.add(array[i]);
        }
    }
    return false;
}

var arr = [1, 2, 3, 4, 5, 6];
console.log(hasDuplicates(arr)); // Output: false

var arrWithDuplicates = [1, 2, 3, 4, 4, 5];
console.log(hasDuplicates(arrWithDuplicates)); // Output: true
Enter fullscreen mode Exit fullscreen mode

Both of these functions will return true if the array contains duplicate values, and false otherwise. Choose the implementation (Object or Set) based on your preference and compatibility requirements.

Top comments (0)