Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

marked as duplicate by j08691, Bergi, Bobrovsky, Filburt, Ben D Oct 4 '12 at 20:38

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
See if any of these solutions help: stackoverflow.com/questions/840781/… –  Chase Oct 4 '12 at 17:21
4  
This is a surprisingly good function for someone who's new to JS. +1 –  NullUserException Oct 4 '12 at 17:24
1  
@NullUserException tnx, what do you mean it doesn't really work? are you talking about the code I've written? I tested it and it works. –  sheidaei Oct 4 '12 at 17:27
2  
Your code should work fine, but this question should probably be on codereview.stackexchange.com instead of this site. –  I Hate Lazy Oct 4 '12 at 17:30
2  
@sheidaei: Your functions considers values as equal (duplicate) if they cast to the same string (i.e. it works for an array of strings, but not for arrays of objects etc) –  Bergi Oct 4 '12 at 17:32

4 Answers 4

up vote 1 down vote accepted

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;
}
share|improve this answer

// You would only need to optimize it if you want to use it elsewhere-

function noduplicates(array){
    var next, O= {},
    L= array.length;
    while(L){
        next= array[--L];
        if(O[next]) return false;
        O[next]= 1;
    }
    return true;
}


function validatePassTimeFields(passtimes){
    if (noduplicates(passtimes)) return true;

    alert("Duplicate Found");
    return false;
}
share|improve this answer
    
I am testing your code jsfiddle.net/GubnU and it works fine. However, when I am running it locally I have to change the line where you assign the next value to the following: next= array[--L].value; Any idea why? –  sheidaei Oct 4 '12 at 18:25

It might be worth checking out underscore's implementation of this functionality. If you are just looking to eliminate dupes, you can use _.uniq(), but if you are more interested in just knowing that there are dupes or the pure implementation details, you might enjoy checking out the source of this method, which is very nicely documented.

I know this isn't a direct code answer to the question - there are a few here already so it wouldn't be useful to repeat. But I thought it was worth mentioning as underscore is a great utility library and the source is a great place to learn more about well-written javascript.

share|improve this answer

It seems that you do not want to find the duplicates, only to see if there are any?

You're pretty close, here's a working function;

var hasDuplicates = function (arr) {

    var _store = {};

    for (var i = 0; i < arr.length; i++) {

        if (typeof _store["_" + arr[i]] !== "undefined") {
            return true;
        }

        _store["_" + arr[i]] = true;

    }

    return false;

};

The underscores in the associative array are necessary for storing numeric values. The hasDuplicates() function only works objects which have a toString() method.

To check for duplicates;

var yourArray  = [1, 5, 7, 3, 5, 6];

if (hasDuplicates(yourArray)) {...
share|improve this answer
    
Great solution. Clear and simple. –  Michael Sazonov Oct 4 '12 at 17:56
1  
Why do you use so many underscores? –  Bergi Oct 4 '12 at 18:28
1  
Don't use typeof void 0(or typeof _undef), just use "undefined". –  Bergi Oct 4 '12 at 18:30
1  
@Björn: That makes no sense to me. With the var keyword you declare them to be local, no underscore needed. The underscore is mostly used for semi-private (but actually exposed) properties –  Bergi Oct 4 '12 at 18:31
1  
@sheidaei - I always have an undefined variable in my modules, bad habit I guess. –  Björn Oct 4 '12 at 19:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.