You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写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:

  1. 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"]].
  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 obj is 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 arr doesn’t have a key from obj, item[key] will be undefined, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 16:34:04