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

寻求无需使用for循环的二维数组精确子数组匹配统计实现方法

Solution for Matching 2D Array Subarrays Without For Loops

Let's fix this up for you! Your original code has a few critical issues that are stopping it from working correctly, and we can implement the required logic using JavaScript/TypeScript array higher-order functions (no explicit for loops needed) to get the exact results you want.

What Was Wrong With the Original Code?

  • You were targeting arr[0].filter which only processes the first subarray of arr1, not every subarray in the list
  • The subarrays are arrays of strings, so there's no id property to reference (that part of the code was completely misplaced)
  • The function didn't return any value, and the map result was never saved or used

Working Implementation

Here's a corrected version that returns both the per-subarray match results and the total count of matches:

const arr1: string[][] = [ ["R", "P"], ["R", "S"], ["S", "P"], ];
const checkAgainst: string[][] = [ ["R", "S"], ["P", "R"], ["S", "P"], ];

function check(arr: string[][]) {
  // Generate a boolean array showing match status for each subarray in arr1
  const matchResults = arr.map(subArr => 
    checkAgainst.some(targetSubArr => 
      // First ensure subarrays are the same length, then verify every element matches
      subArr.length === targetSubArr.length && 
      subArr.every((element, index) => element === targetSubArr[index])
    )
  );

  // Count how many true values are in matchResults
  const matchCount = matchResults.reduce((total, isMatch) => total + (isMatch ? 1 : 0), 0);

  return { matchResults, matchCount };
}

// Run the function and log results
const result = check(arr1);
console.log("Per-subarray match results:", result.matchResults); // Output: [false, true, true]
console.log("Total matching subarrays:", result.matchCount); // Output: 2

How This Works

  • map: Iterates over every subarray in arr1 and generates a corresponding boolean value for each one
  • some: Checks if there's at least one subarray in checkAgainst that matches the current subarray from arr1
  • every: Ensures every element in the current subarray matches the corresponding element in the target subarray (we also check length first to avoid mismatches from arrays of different sizes)
  • reduce: Tallies up the number of true values in the matchResults array to get the total count of successful matches

内容的提问来源于stack exchange,提问作者Goaul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 19:24:07