Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search through an array in Javascript? [duplicate]

Tags:

javascript

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?

like image 359
sheidaei Avatar asked Oct 04 '12 17:10

sheidaei


1 Answers

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:

  • Don't use the success variable and break from the loop, but just return from the whole function.
  • Instead of the constructor new Object usually the shortcut object literal {} is used
  • Instead of setting the values in the hashMap 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;
}
like image 72
Bergi Avatar answered Nov 15 '22 00:11

Bergi