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
1 Answer
Reset to default 7Use 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");
}
}