Find the count of duplicate property values in an object

扶醉桌前 提交于 2019-12-08 03:38:22

问题


var db = [
  {Id: "201" , Player: "Nugent",Position: "Defenders"},
  {Id: "202", Player: "Ryan",Position: "Forwards"},
  {Id: "203" ,Player: "Sam",Position: "Forwards"},
  {Id: "204", Player: "Bill",Position: "Midfielder"},
  {Id: "205" ,Player: "Dave",Position: "Forwards"},
];

How can I can I find the number of duplicate objects by Position.

Notice I have duplicated value as "Forwards" (second, third and last object)

I have tried doing:

for (var key in db) {
  var value = db[key];
  if ( count of duplicated values == 3) {
    console.log("we have three duplicated values)
  }
}

Is it possible to do this while the objects are being looped?


回答1:


Use another object as a counter, like this

var counter = {};
for (var i = 0; i < db.length; i += 1) {
    counter[db[i].Position] = (counter[db[i].Position] || 0) + 1;
}

for (var key in counter) {
    if (counter[key] > 1) {
        console.log("we have ", key, " duplicated ", counter[key], " times");
    }
}


来源:https://stackoverflow.com/questions/27644141/find-the-count-of-duplicate-property-values-in-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!