sandrooco
sandrooco

Reputation: 8716

Check if an object exists twice in an array

I have an array containing objects with this structure:

var results = [{
    AuthorId: 2,
    Id: 89,
    caseId: 33 //some key
},...];

Now, I want to check if the objects in this array exist 2 or more times and log them in the console.

My approach:

$.each(results, function (i, result) {
    var stringRes = result.AuthorId + ";" + result.caseId;
    $.each(results, function (j, toTest) {
        if (j <= results.length - 2) {
            var stringToTest = results[j + 1].AuthorId + ";" + results[j + 1].caseId;
            if (stringToTest == stringRes) {
                console.log(result.Id);
                //some function to do something with duplicates
            }
         }
    });
});

Firstly, I know making strings and comparing them isn't really good. Secondly, this will log every item at least once, because every item compares to each other (= the item compares itself to itself).

Is this fixable with a (more or less) fast and reliable way?

Upvotes: 2

Views: 1635

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386604

You could use a hash table or a map for counting. If the count is 2 or greater make something. As key, I suggest to use the stringified object, if the object has always the same structure.

var results = [{ AuthorId: 2, Id: 89, caseId: 33 }, { AuthorId: 2, Id: 89, caseId: 33 }],
    hash = Object.create(null);

results.forEach(function (a) {
    var key = JSON.stringify(a);
    hash[key] = (hash[key] || 0) + 1;
    if (hash[key] >= 2) {
        console.log('count of 2 or more of ' + key);
    }
});

Upvotes: 1

Related Questions