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.