问题
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