2

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

you may add some more data, to test.
Tested with 2300 items. :)
the check, if the structure, the json string is equal.
Whoops, makes sense - of course the id is unique so the multiple logs are just normal. Thanks alot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.