Count Items Matching a Rule

easy array string counting

Problem

Each items[i] = [type, color, name]. A rule is two strings, ruleKey and ruleValue. The key picks a column: "type" → column 0, "color" → column 1, "name" → column 2. An item matches when that column equals ruleValue. Return how many items match.

Inputitems = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
Output1
Only ["computer","silver","lenovo"] has color "silver".

def countMatches(items, ruleKey, ruleValue):
    # map the rule key to the column it refers to
    idx = {"type": 0, "color": 1, "name": 2}[ruleKey]
    count = 0
    for item in items:
        if item[idx] == ruleValue:   # compare just that column
            count += 1
    return count
function countMatches(items, ruleKey, ruleValue) {
  // map the rule key to the column it refers to
  const idx = { type: 0, color: 1, name: 2 }[ruleKey];
  let count = 0;
  for (const item of items) {
    if (item[idx] === ruleValue) {   // compare just that column
      count++;
    }
  }
  return count;
}
int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
    // map the rule key to the column it refers to
    int idx = ruleKey.equals("type") ? 0 : ruleKey.equals("color") ? 1 : 2;
    int count = 0;
    for (List<String> item : items) {
        if (item.get(idx).equals(ruleValue)) {   // compare just that column
            count++;
        }
    }
    return count;
}
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
    // map the rule key to the column it refers to
    int idx = ruleKey == "type" ? 0 : ruleKey == "color" ? 1 : 2;
    int count = 0;
    for (auto& item : items) {
        if (item[idx] == ruleValue) {   // compare just that column
            count++;
        }
    }
    return count;
}
Time: O(n) Space: O(1)