Intersection of two arrays II JavaScript

Intersection of two arrays II JavaScript

Urfan Guliyev

Posted on Jul 12, 2020 • Updated on Jul 19, 2020

Today I am going to show how to solve the Leetcode Intersection of Two Arrays algorithm problem.

Here is the problem:

Intersection of two arrays II JavaScript

Solution:
There are no built-in methods in JavaScript for computing an intersection. That's why I use a new data structure, Set, which was introduced in ECMAScript 2015. As you know, set objects are collections of unique values.

First, I use Set to store both arrays. Then, I create an array from a set1 using the spread operator. I filter through the array to select the elements that are also in the second set object (set2).

var intersection = function(nums1, nums2) { let set1 = new Set(nums1); let set2 = new Set(nums2); let output = [...set1].filter(x => set2.has(x)) return output };

Once suspended, urfan will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, urfan will be able to comment and publish posts again.

Once unpublished, all posts by urfan will become hidden and only accessible to themselves.

If urfan is not suspended, they can still re-publish their posts from their dashboard.

Note:

Thanks for keeping DEV Community 👩‍💻👨‍💻 safe. Here is what you can do to flag urfan:

Make all posts by urfan less visible

urfan consistently posts content that violates DEV Community 👩‍💻👨‍💻's code of conduct because it is harassing, offensive or spammy.

Report other inappropriate conduct

Unflagging urfan will restore default visibility to their posts.

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

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9]

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ const intersect = (nums1, nums2) => { const map = nums1.reduce( (acc, num1) => { if (acc[num1]) { acc[num1] += 1 } else { acc[num1] = 1 } return acc }, {}, ) return nums2.filter((num2) => { if (map[num2]) { map[num2] -= 1 return true } return false }) }

To get the difference of two arrays in JavaScript, you can use the combination of filter and includes. Imagine you have the following two arrays and you want to find out which elements are included in both:

const veggies = ['🍅', '🥕', '🥒']; const fruits = ['🍓', '🍌', '🍅'];

Copied to clipboard!

To get their intersection, you can use the following call:

const intersection = veggies.filter(v => fruits.includes(v));

Copied to clipboard!

To get their differencem eg.: only the ones that veggies include, you can do the following:

const difference = veggies.filter(v => !fruits.includes(v)); const difference = fruits.filter(f => !veggies.includes(f));

Copied to clipboard!

And in order to get the symmetric difference of two arrays — meaning leave out the ones that are in both arrays — you need to filter both of them and either use concat or destructuring:

const symmetricDifference = [ ...veggies.filter(v => !fruits.includes(v)), ...fruits.filter(f => !veggies.includes(f)) ];

Copied to clipboard!

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.

Intersection of two arrays II JavaScript

If you need to rely on the same logic multiple times in your codebase, you can reuse them with the following function calls:

const intersect = (a, b) => a.filter(a => b.includes(a)); const difference = (a, b) => a.filter(a => !b.includes(a)); const symmetric = (a, b) => [ ...a.filter(a => !b.includes(a)), ...b.filter(b => !a.includes(b)) ];

Copied to clipboard!

Intersection of two arrays II JavaScript
If you would like to see more Webtips, follow @flowforfrank
Intersection of two arrays II JavaScript

Resources:

  • Array.prototype.filter
  • Array.prototype.includes

Please provide a valid email address.

You are already subscribed to our newsletter.

Intersection of two arrays II JavaScript

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in 5 hours.

Learn More

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. ☕

Get access
Intersection of two arrays II JavaScript

Read more on
Intersection of two arrays II JavaScript

Intersection of two arrays II JavaScript
report this ad