我有一个包含具有此结构的对象的数组:
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
}
}
});
});
首先,我知道制作字符串并进行比较并不是很好。其次,这将至少记录一次每个项目,因为每个项目彼此比较(=项目将自身与其自身进行比较)。
是否可以(或多或少)快速而可靠地解决此问题?
您可以使用哈希表或地图进行计数。如果计数为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);
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句