首页 > 其他分享 >统计匹配检索规则的物品数量

统计匹配检索规则的物品数量

时间:2022-10-29 23:01:46浏览次数:42  
标签:检索 匹配 color items ruleValue ruleKey phone 物品 type

统计匹配检索规则的物品数量_iphone

题目

给你一个数组 items ,其中 items[i] = [typei, colori, namei] ,描述第 i 件物品的类型、颜色以及名称。

另给你一条由两个字符串 ruleKey 和 ruleValue 表示的检索规则。

如果第 i 件物品能满足下述条件之一,则认为该物品与给定的检索规则 匹配 :

ruleKey == "type" 且 ruleValue == typei 。 ruleKey == "color" 且 ruleValue == colori 。 ruleKey == "name" 且 ruleValue == namei 。 统计并返回 匹配检索规则的物品数量 。


示例 1:
输入:items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
输出:1
解释:只有一件物品匹配检索规则,这件物品是 ["computer","silver","lenovo"] 。

示例 2:
输入:items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"
输出:2
解释:只有两件物品匹配检索规则,这两件物品分别是 ["phone","blue","pixel"] 和 ["phone","gold","iphone"] 。注意,["computer","silver","phone"] 未匹配检索规则。


提示:
1 <= items.length <= 104
1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10
ruleKey 等于 "type"、"color" 或 "name"
所有字符串仅由小写字母组成

题解

定义一个map,用于定位ruleKey所在的索引; 循环二维数组,查找二维数组的每个元素(一位数组)[ruleKey所在的索引] 是否等于ruleValue;

var countMatches = function(items, ruleKey, ruleValue) {
let num = 0;
let map = new Map();
map = {
type : 0,
color: 1,
name: 2
}

const index = map[ruleKey];
items.forEach((eles) => {
if (eles[index] === ruleValue) {
num++;
}
})
return num;
};

或者:

根据题意item 是由 [type, color, name]组成的二维数组, 通过map定义三个属性的下标{type: 0,color: 1,name: 2 }并根据ruleKey动态取出来,剩下的一个 filter 就搞定了

/**
* @param {string[][]} items
* @param {string} ruleKey
* @param {string} ruleValue
* @return {number}
*/
var countMatches = function(items, ruleKey, ruleValue) {
return items.filter(item =>item[{type: 0,color: 1,name: 2 }[ruleKey]] === ruleValue).length
};

标签:检索,匹配,color,items,ruleValue,ruleKey,phone,物品,type
From: https://blog.51cto.com/u_13961087/5806591

相关文章