What's the simplest, library-free code for implementing array intersections in javascript?
Simplest, Library-Free Code for Implementing Array Intersections in JavaScript
To find the intersection of two arrays (i.e., elements that are present in both arrays), you can use basic JavaScript constructs like filter, includes, and Set for an efficient and straightforward solution. Below are a couple of methods to achieve this without using any external libraries.
Method 1: Using filter and includes
This method is straightforward and easy to understand. It uses the filter method to iterate over one array and the includes method to check if each element is present in the other array.
Example:
function arrayIntersection(arr1, arr2) { return arr1.filter(value => arr2.includes(value)); } // Example usage: const array1 = [1, 2, 3, 4, 5]; const array2 = [4, 5, 6, 7, 8]; const intersection = arrayIntersection(array1, array2); console.log(intersection); // Output: [4, 5]
Method 2: Using Set for Improved Efficiency
Using a Set can improve efficiency, especially for larger arrays, because lookups in a Set are generally faster than lookups in an array.
Example:
function arrayIntersection(arr1, arr2) { const set2 = new Set(arr2); return arr1.filter(value => set2.has(value)); } // Example usage: const array1 = [1, 2, 3, 4, 5]; const array2 = [4, 5, 6, 7, 8]; const intersection = arrayIntersection(array1, array2); console.log(intersection); // Output: [4, 5]
Method 3: Using reduce and Set for a More Functional Approach
This method leverages reduce and Set for a more functional programming style. It combines the uniqueness of Set with the power of reduce to create a concise solution.
Example:
function arrayIntersection(arr1, arr2) { const set2 = new Set(arr2); return arr1.reduce((acc, value) => { if (set2.has(value)) { acc.push(value); } return acc; }, []); } // Example usage: const array1 = [1, 2, 3, 4, 5]; const array2 = [4, 5, 6, 7, 8]; const intersection = arrayIntersection(array1, array2); console.log(intersection); // Output: [4, 5]
Summary
- Method 1 (Using
filterandincludes): Simple and readable, suitable for small arrays. - Method 2 (Using
Setfor Efficiency): Faster lookups, better performance for larger arrays. - Method 3 (Using
reduceandSet): More functional approach, combinesreduceandSetfor a concise solution.
Each of these methods provides a straightforward way to find the intersection of two arrays in JavaScript without relying on external libraries. For more in-depth knowledge and practical examples of JavaScript and other programming concepts, consider exploring Grokking the Coding Interview on DesignGurus.io, which offers comprehensive courses on essential coding and interview techniques.
GET YOUR FREE
Coding Questions Catalog
$197

$78
$78