8

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?

19
  • 1
    See if any of these solutions help: stackoverflow.com/questions/840781/… Commented Oct 4, 2012 at 17:21
  • 4
    This is a surprisingly good function for someone who's new to JS. +1 Commented Oct 4, 2012 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. Commented Oct 4, 2012 at 17:27
  • 2
    Your code should work fine, but this question should probably be on codereview.stackexchange.com instead of this site. Commented Oct 4, 2012 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) Commented Oct 4, 2012 at 17:32

4 Answers 4

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

// 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;
}

1 Comment

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?
0

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.

Comments

0

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)) {...

8 Comments

Great solution. Clear and simple.
Why do you use so many underscores?
Don't use typeof void 0(or typeof _undef), just use "undefined".
@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
@sheidaei - I always have an undefined variable in my modules, bad habit I guess.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.