1

I would like to know how i can count the number of duplicate keys in my object.

My object is "a" and i have got the keys of this object using keys(a)

keys(a) = ["name", "key", "com", "com"]

How can i find the total number of times "com" exists in the above? I should get a length of 2.

thanks in advance

2 Answers2

2

No, JavaScript objects cannot have duplicate keys. The keys must all be unique. There is a good thread on Stack Overflow on this topic.

If suppose you have array of objects its possible. Use another object as a counter, like this

var db = [
        {Id: "1" , Player: "Nugent",Position: "Defenders"},
        {Id: "2", Player: "Ryan",Position: "Forwards"},
        {Id: "3" ,Player: "Sam",Position: "Forwards"},
        {Id: "4", Player: "Bill",Position: "Midfielder"},
        {Id: "5" ,Player: "Dave",Position: "Forwards"},
        {Id: "6", Player: "Bill",Position: "Midfielder"}
]

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");
    }
}
Community
  • 1
  • 1
Keshan Nageswaran
  • 8,060
  • 3
  • 28
  • 45
1

Ignoring the fact that an object can't have duplicate keys (or assuming that your keys() function allows for nested objects), and just dealing with the question of how to count how many times a particular value appears in an array, a simple way is just to use the array .filter() method and then check the .length of the resulting array:

var keys = ["name", "key", "com", "com"];
var comCount = keys.filter(v => v === "com").length;
console.log(comCount); // 2

If you need to support older browsers that don't do ES6 arrow functions then:

keys.filter(function(v) { return v === "com"; }).length;

Or wrapped in a custom function if you need to do this a lot:

function countValueInArray(val, arr) {
  return arr.filter(v => v === val).length;
}

var keys = ["name", "key", "com", "com"];

console.log(countValueInArray("com", keys));  // 2
console.log(countValueInArray("abc", keys));  // 0
console.log(countValueInArray("key", keys));  // 1

Or you could manually code a for loop. Or use .reduce(). Etc.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241