检查数组中是否存在两次对象

时间:2016-12-01 10:00:55

标签: javascript arrays loops compare javascript-objects

我有一个包含具有这种结构的对象的数组:

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

现在,我想检查此数组中的对象是否存在2次或更多次,并将其记录在控制台中。

我的方法:

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

首先,我知道制作字符串并比较它们并不是很好。其次,这将至少记录一次每个项目,因为每个项目相互比较(=项目将自身与自身进行比较)。

这可以通过(或多或少)快速可靠的方式进行修复吗?

1 个答案:

答案 0 :(得分:0)

您可以使用哈希表或地图进行计数。如果计数是2或更大的东西。作为关键,如果对象始终具有相同的结构,我建议使用字符串化对象。

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