Possible Duplicate:
Easiest way to find duplicate values in a JavaScript array
I am looking to find if two values are the same in an Array. I have written the following code:
function validatePassTimeFields(passtimes) {
    var success = true; 
    var length = passtimes.length;
    var hashMap = new Object();
    for (var j=0; j<length; j++) {
        if(hashMap[passtimes[j].value]==1) {
            success = false;
            alert("Duplicate Found");
            break;
        }
        hashMap[passtimes[j].value]=1;
    }
    return success;
}
I am new to Javascript, so I tried using HashMap like to find if there is any duplicate. IS it the best way of finding a duplicate in JavaScript? or I can optimize it?
Your function is already very good, apart from the issue that it only works for arrays with strings or numbers. For a more difficile approach to care also about objects see this answer. I don't think that matters for you as you have an explicit and restricted use case (checking identity by the value property).
However, some points I'd do different:
success variable and break from the loop, but just return from the whole function.new Object usually the shortcut object literal {} is usedhashMap to 1 one might use true; you also could omit the equality operator == and just check for the truthiness of the property. I even would use the in operator.function validatePassTimeFields(passtimes) {
    var length = passtimes.length;
    var hashMap = {};
    for (var j=0; j<length; j++) {
        if (passtimes[j].value in hashMap) {
            alert("Duplicate Found");
            return false;
        }
        hashMap[passtimes[j].value] = 1;
    }
    return true;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With