2022/12/24

LeetCode 1773. Count Items Matching a Rule

問題:計算根據規則找到對應的搜尋值數量 解法:先將規則轉換為key,用filter即可 JavaScript
/**
 * @param {string[][]} items
 * @param {string} ruleKey
 * @param {string} ruleValue
 * @return {number}
 */
var countMatches = function (items, ruleKey, ruleValue) {
    if (items.length < 1 || items.length > Math.pow(10, 4)) {
        return;
    }

    const key = ruleKey === 'type' ? 0 : ruleKey === 'color' ? 1 : 2;
    return items.filter(s => s[key] === ruleValue).length;
};