最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Find the count of duplicate property values in an object - Stack Overflow

programmeradmin0浏览0评论
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?

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?

Share Improve this question edited Jul 4, 2018 at 10:55 Ivan 40.9k8 gold badges73 silver badges117 bronze badges asked Dec 25, 2014 at 4:07 user3157259user3157259 271 silver badge4 bronze badges 1
  • since you have an array of objects, do you need to specify which object property to be duplicated? – hjl Commented Dec 25, 2014 at 4:15
Add a ment  | 

1 Answer 1

Reset to default 7

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");
    }
}
发布评论

评论列表(0)

  1. 暂无评论