编写findMatches函数:筛选数组中匹配指定键值对的对象并返回数组
Solution: Implementing the
findMatches Function To solve this problem, we need to filter an array of objects to retain only those that fully contain all key-value pairs from the provided match rule object. Here's a clean, robust implementation:
function findMatches(arr, obj) { // Convert the match rule object into an array of [key, value] pairs const matchEntries = Object.entries(obj); // Filter the input array to keep only objects that match all rules return arr.filter(item => { // Verify every key-value pair from the rule exists and matches in the current item return matchEntries.every(([key, value]) => item[key] === value); }); }
How It Works
Let’s break down the logic step by step:
- Extract Match Rules:
Object.entries(obj)transforms the match rule object into an array of key-value pairs. For your sample input, this becomes[["X", "1"], ["Y", "2"]]. - Filter the Array: We use
arr.filter()to loop through each object in the input array. For each object:matchEntries.every(...)checks if all key-value pairs from the rule are present and equal in the current item. If even one pair doesn’t match, the object is excluded from the result.
Example Test
Let’s run your sample input through the function:
const inputArr = [ {"X" : "1", "Y" : "2","Z" : "4", "P" : "5"}, {"X" : "2", "Y" : "2","Z" : "4", "P" : "5"}, {"X" : "1", "Y" : "2","Z" : "9", "P" : "6"} ]; const matchObj = {"X":"1", "Y":"2"}; console.log(findMatches(inputArr, matchObj));
Output:
[ {"X" : "1", "Y" : "2","Z" : "4", "P" : "5"}, {"X" : "1", "Y" : "2","Z" : "9", "P" : "6"} ]
Which matches exactly what you expected!
Edge Cases Handled
- Empty match object: If
objis empty, the function returns the entire input array (since every object trivially contains zero key-value pairs). - Empty input array: Returns an empty array, as there’s nothing to filter.
- Match object with multiple keys: Works regardless of how many key-value pairs you need to check.
- Non-existent keys: If an object in
arrdoesn’t have a key fromobj,item[key]will beundefined, which won’t match the rule’s value, so it gets excluded.
This implementation is concise, readable, and handles all valid input scenarios as required.
内容的提问来源于stack exchange,提问作者Anistan Yoganath
相关产品推荐
相关产品推荐

