JavaScript如何比较输入数组:实现intersection函数求解交集
Solution for the
intersection Function Hey there, sorry you've been stuck on this for 3 days—let's break this down and fix it together! The goal is to write a function that takes multiple arrays and returns only the elements that exist in all of them.
Approach
Here's a straightforward, efficient way to tackle this:
- Handle edge cases first: If the input is an empty list of arrays, return an empty array immediately to avoid errors.
- Optimize lookups: Convert each input array to a
Set—this turns slow O(n) element checks into O(1) operations, which is way faster, especially for large arrays. - Check common elements: Use the first array's Set as a starting point, then filter its elements to keep only those that exist in every other Set.
Working Code
function intersection(arrayOfArrays) { // Return empty array if no input arrays are provided if (arrayOfArrays.length === 0) return []; // Convert each input array to a Set for faster lookups const arrayOfSets = arrayOfArrays.map(arr => new Set(arr)); // Use the first set as our reference point const referenceSet = arrayOfSets[0]; // Filter elements that exist in ALL sets return Array.from(referenceSet).filter(element => { return arrayOfSets.every(set => set.has(element)); }); } // Test the function—should output [5, 15] console.log(intersection([[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]]));
How It Works
- Set conversion: Turning each array into a Set eliminates duplicate elements within individual arrays and gives us access to the lightning-fast
has()method for existence checks. - Filter with
every(): Theevery()method ensures we only keep elements that are present in every input array. If even one array doesn't contain the element, it gets filtered out. - Edge case handling: We start by checking if the input is empty to avoid errors when trying to access the first array.
Alternative (Simpler for Small Arrays)
If you're working with small arrays and don't need the performance boost of Sets, you can use a more basic version:
function intersection(arrayOfArrays) { if (arrayOfArrays.length === 0) return []; // Get unique elements from the first array to avoid duplicates in results const uniqueFirst = [...new Set(arrayOfArrays[0])]; return uniqueFirst.filter(element => { return arrayOfArrays.every(arr => arr.includes(element)); }); }
This does the same job but uses includes() instead of Set has()—it's easier to read but less efficient for large datasets.
Hope this gets you unstuck! Feel free to ask if you need to clarify any part of the code.
内容的提问来源于stack exchange,提问作者sgt.ahn
相关产品推荐
相关产品推荐

