如何快速枚举两个大数组并找出匹配元素的索引对?
Find Matching Element Indices Between Two 2D Arrays
Got it, let's solve this problem where we need to find all index pairs [i, j] where the element at data1[i] matches data2[j].
Approach
Since we're dealing with arrays of arrays, we can't just use direct equality checks (because arrays are reference types in most languages). Instead, we'll:
- Iterate over each element in
data1along with its indexi. - For each element in
data1, iterate over every element indata2with its indexj. - Compare the inner arrays for value equality (not reference).
- If they match, add the index pair
[i, j]to our result list.
Solution Code (JavaScript)
First, let's write a helper function to check if two flat arrays are equal:
function arraysEqual(arr1, arr2) { // First check if lengths match if (arr1.length !== arr2.length) return false; // Compare each element one by one for (let k = 0; k < arr1.length; k++) { if (arr1[k] !== arr2[k]) return false; } return true; }
Then the main function to collect matching indices:
function findMatchingIndices(data1, data2) { const result = []; // Loop through each element in data1 for (let i = 0; i < data1.length; i++) { const currentElem = data1[i]; // Check every element in data2 for a match for (let j = 0; j < data2.length; j++) { if (arraysEqual(currentElem, data2[j])) { result.push([i, j]); } } } return result; }
Test with Your Sample Data
Let's plug in your example values:
const data1 = [[1,1],[2,5],[623,781]]; const data2 = [[1,1], [161,74],[357,17],[1,1]]; console.log(findMatchingIndices(data1, data2)); // Output: [[0, 0], [0, 3]] → exactly what you expected!
Notes
- This solution works for flat inner arrays (like the 2-element arrays in your example). If you have deeper nested arrays, you'd need a recursive equality check instead of the simple
arraysEqualfunction. - If your arrays are very large, nested loops might not be the most efficient (O(n*m) time complexity). For larger datasets, you could pre-process
data2into a map where the key is a stringified version of the array, and the value is an array of indices. That would bring the time complexity down to O(n + m). For example:
This optimized version is better for large datasets, but the nested loop approach is simpler and works fine for smaller arrays.function findMatchingIndicesOptimized(data1, data2) { const data2Map = new Map(); // Preprocess data2: map stringified array to list of indices for (let j = 0; j < data2.length; j++) { const key = JSON.stringify(data2[j]); if (!data2Map.has(key)) { data2Map.set(key, []); } data2Map.get(key).push(j); } const result = []; for (let i = 0; i < data1.length; i++) { const key = JSON.stringify(data1[i]); if (data2Map.has(key)) { // Add all matching j indices for this i data2Map.get(key).forEach(j => result.push([i, j])); } } return result; }
内容的提问来源于stack exchange,提问作者J. Leung
相关产品推荐
相关产品推荐

