loading...

Leetcode - Intersection of Two Arrays (with JavaScript)

urfan profile image Urfan Guliyev Updated on ・1 min read

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

Here is the problem:
Alt Text

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

};

Discussion

markdown guide
 

Shorter version:

const intersection = (arr1, arr2) => [...new Set(arr1)].filter(x => new Set(arr2).has(x))