寻求无需使用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].filterwhich only processes the first subarray ofarr1, not every subarray in the list - The subarrays are arrays of strings, so there's no
idproperty to reference (that part of the code was completely misplaced) - The function didn't return any value, and the
mapresult 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 inarr1and generates a corresponding boolean value for each onesome: Checks if there's at least one subarray incheckAgainstthat matches the current subarray fromarr1every: 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 oftruevalues in thematchResultsarray to get the total count of successful matches
内容的提问来源于stack exchange,提问作者Goaul
相关产品推荐
相关产品推荐

