How can I code a basic JavaScript function for finding intersections of two arrays without using any libraries? Using the function, I’d like to run:
findCommonElements([4, 5, 6], [5, 6, 7, 8])
and receive
[5, 6]
How can I code a basic JavaScript function for finding intersections of two arrays without using any libraries? Using the function, I’d like to run:
findCommonElements([4, 5, 6], [5, 6, 7, 8])
and receive
[5, 6]
In order to find the intersections of two arrays using JavaScript without relying on external libraries, we can use sets and the filter method. This provides an efficient and readable approach for identifying common elements between arrays. Let’s construct a basic function that performs this task and examine its operation.
function findCommonElements(arr1, arr2) {
const setArr2 = new Set(arr2);
return arr1.filter(item => setArr2.has(item));
}
const result = findCommonElements([4, 5, 6], [5, 6, 7, 8]);
console.log(result); // Output: [5, 6]
Understanding Sets: We begin by converting the second array (arr2
) into a Set
. Sets are collections of unique values, and they provide an efficient way to check if an item exists within the collection.
Filtering: We utilize the filter
method on the first array (arr1
). This method creates a new array with elements that pass the test implemented by the provided function.
Checking for Intersection: Inside the filter operation, we check if each item from arr1
exists in the Set
derived from arr2
. If it does, the element is included in the result array.
Result: The filtered array, containing only the common elements from both input arrays, is returned. In the given example, the function successfully finds that [5, 6]
is common to both input arrays.
This method is optimal when you need to quickly find common elements without the overhead of additional libraries. It’s both effective and maintains excellent readability for those new to JavaScript as well as experienced developers.