DEV Community

Urfan Guliyev
Urfan Guliyev

Posted on • Updated on

Leetcode - Intersection of Two Arrays (with JavaScript)

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

};

Top comments (3)

Collapse
 
pinceladasdaweb profile image
Pedro Rogério

Shorter version:

const intersection = (arr1, arr2) => [...new Set(arr1)].filter(x => new Set(arr2).has(x))
Collapse
 
vishal590 profile image
vishal

but why used set object method, we can do it without set method ?

Collapse
 
vishal590 profile image
vishal

oh so new set is method which holds unique values