Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

ab
ab

Posted on

     

Finding the Intersection of Two Arrays

Today's algorithm is theIntersection of Two Arrays problem:

Given two arrays, write a function to compute their intersection.

Each element in the result has to be unique, and the result can be in any order.

For example, if the two arrays were[3, 5, 3, 2] and[3, 5, 3], the output should be[3, 5], because those are the two unique elements found in both arrays.

This problem is a good instance to make use of sets. Aset is an object of unique values, and are particularly useful in problems where you're told to return unique elements. You can learn more about setshere.

In this post, I'll be discussing how I want to approach this problem, then coding the solution in JavaScript.

Approaching the Problem

In this problem, we're given two arrays, which may both have repeating numbers in them, and we only want to return unique, shared values. One way to solve this is by turning the first array into a set, which will remove any duplicate values.

Turning an array into a set is actually a very short process. Let's say you had an array calledarr1, which was equal to[2, 4, 4], and wanted to create a set based on that array:

  const set1 = new Set(arr1)
Enter fullscreen modeExit fullscreen mode

Based on the above statement,set1 will equal{2, 4}.

Once we turn the first given array into a set, we can then go through each element of the second given array, and check if it's in the set. If it is, we'll add it to a result array, which we'll return at the end. We'll also want to remove that element from the set, so that if the second array has a duplicate value, we don't add it to the result array twice.

To check if a set has an element, we can use thehas() method, which returns a boolean value (true or false). For example, if we're still working withset1 from above:

  const arr1 = [2, 4, 4]  const set1 = new Set(arr1) // {2, 4}  set1.has(2) // will return true  set1.has(5) // will return false
Enter fullscreen modeExit fullscreen mode

To remove an element from a set, we can use thedelete() method, which removes a specific element from a set. To continue with the same example:

  const arr1 = [2, 4, 4]  const set1 = new Set(arr1) // {2, 4}  set1.delete(2) // set1 = {4}
Enter fullscreen modeExit fullscreen mode

Coding the Solution

With the above methods in mind, we can start out by creating a new set based onnums1, which is the first inputted array. We can do this by setting a new variable calledset equal tonew Set(nums1).

We also can create a new array calledresult, which we'll start as an empty array. This array will be returned at the end of the function, so we can include the result statement now.

functionintersection2(nums1,nums2){letset=newSet(nums1);letresult=[];//...returnresult;}
Enter fullscreen modeExit fullscreen mode

Now, we'll want to check each value ofnums2 to see if it's inset. To do this, we can set up a for loop, which will iterate through each value ofnums2, and therefore will go from 0 until the length of thenums2 array.

functionintersection2(nums1,nums2){letset=newSet(nums1);letresult=[];for(leti=0;i<nums2.length;i++){//...}returnresult;}
Enter fullscreen modeExit fullscreen mode

Inside the for loop, we'll want to check if the set has each element ofnums2. Each element ofnums2 is accessed withnums2[i]. We then can create a conditional statement to see if the set has that element, usingset.has(nums2[i]).

If this returns true, then we'll want to do two things: first, we'll want to add the element to the result array, using.push(). We'll then want to delete that element fromset, so that we don't add duplicate values to theresult array.

functionintersection2(nums1,nums2){letset=newSet(nums1);letresult=[];for(leti=0;i<nums2.length;i++){if(set.has(nums2[i])){result.push(nums2[i]);set.delete(nums2[i]);}}returnresult;}
Enter fullscreen modeExit fullscreen mode

This will return an array containing unique values shared by both arrays.

--

Let me know if you have any questions or alternate solutions to finding the intersection of two arrays.

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
saleemmalikraja profile image
Saleem Malik
Passionate developer and trainer
  • Education
    Master of Engineering in Computer and communication
  • Work
    Front end developer
  • Joined

function intersection1(array1,array2){
// Use polyfill if you are concerning about IE11
//or
// go with indexOf instead of includes
return array1.filter(value => array2.includes(value));

}

intersection1([2,4,5,4] , [0,5]) // will result [5]

(: Happy coding :)

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Joined

More fromab

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp