The title

You are given an array of items where items[I] = [typei, colori, namei] describes the type, color, and name of the ith item.

You are also given a search rule represented by two strings, ruleKey and ruleValue.

Article I is considered to match the given retrieval rule if it satisfies one of the following criteria:

  • RuleKey == “type” and ruleValue == typei.
  • RuleKey == “color” and ruleValue == colori.
  • RuleKey == “name” and ruleValue == namei.

Counts and returns the number of items that match the retrieval rule.

Example 1:

Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", RuleValue = "silver" Output: 1 Explanation: Only one item matches the search rules, and that item is ["computer"," Silver "," Lenovo "].Copy the code

Example 2:

Input: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", RuleValue = "phone" Output: 2 Explanation: Only two items match the search rules, these are ["phone","blue"," Pixel "] and ["phone","gold"," iPhone "]. Note that ["computer","silver","phone"] did not match the search rule.Copy the code

Tip:

  • 1 <= items.length <= 104
  • 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10
  • RuleKey equals “type”, “color”, or” name”
  • All strings consist of lowercase letters only

Their thinking

This is a simple matching problem. We first judge whether the value passed in is the type, color or name, and then traverse the array to record the number of successful matches with it. Finally, the sum is accumulated and returned

Reduce parameters (Explain if you do not understand reduce parameters)

The problem solving

/** * @param {string[][]} items * @param {string} ruleKey * @param {string} ruleValue * @return {number} */ var CountMatches = function(items, ruleKey, ruleValue) {countMatches = function(items, ruleKey, ruleValue) {countMatches = function(items, ruleKey, ruleValue) {const map = {type: 0, color: 1, name: If (curr[map[ruleKey]] === ruleValue) {acc ++} return ACC; if(curr[map[ruleKey]] === ruleValue) {acc ++} return acc; },0) // Pass 0} by default;Copy the code

This article is participating in the “Gold Digging 2021 Spring Recruitment Campaign”, click to see the details of the campaign