---
# System prepended metadata

title: 1773. Count Items Matching a Rule

---

# 1773. Count Items Matching a Rule

## 題目概要

給定一陣列，每個元素也是陣列，陣列中包含三個元素分別為：type, color, name，題目會給定 ruleKey (type, color, name) 及 ruleValue，我們需要找出陣列中包含這個 ruleKey 和 ruleValue 的元素有幾個。

```
Example 1:

Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
Output: 1
Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"].

Example 2:

Input: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"
Output: 2
Explanation: There are only two items matching the given rule, which are ["phone","blue","pixel"] and ["phone","gold","iphone"]. Note that the item ["computer","silver","phone"] does not match.
```

## 解題技巧

- 無


## 程式碼

第一種：

```javascript=
/**
 * @param {string[][]} items
 * @param {string} ruleKey
 * @param {string} ruleValue
 * @return {number}
 */
var countMatches = function(items, ruleKey, ruleValue) {
    let result = 0;

    for(let i = 0; i < items.length; i++) {
        switch (ruleKey) {
            case 'type':
                if (items[i][0] === ruleValue) result++;
                break;
            case 'color':
                if (items[i][1] === ruleValue) result++;
                break;
            case 'name':
                if (items[i][2] === ruleValue) result++;
                break;
        }
    }
    return result;
};

```

![](https://i.imgur.com/TBPzdek.png)

第二種：

```javascript=
/**
 * @param {string[][]} items
 * @param {string} ruleKey
 * @param {string} ruleValue
 * @return {number}
 */
var countMatches = function(items, ruleKey, ruleValue) {
    const ruleList = ['type', 'color', 'name'];
    const key = ruleList.findIndex(f => f === ruleKey);
    let result = 0;

    for (let i = 0; i < items.length; i++) {
        if (items[i][key] === ruleValue) result++;
    }
    
    return result;
};
```

第三種：

```javascript=
/**
 * @param {string[][]} items
 * @param {string} ruleKey
 * @param {string} ruleValue
 * @return {number}
 */
var countMatches = function(items, ruleKey, ruleValue) {
    const ruleList = {
        type: 0,
        color: 1,
        name: 2
    }
    const key = ruleList[ruleKey];

    let result = 0;
    items.forEach(item => item[key] === ruleValue ? result++ : null)

    return result;
};
```

