Today I am going to show how to solve the Leetcode Intersection of Two Arrays algorithm problem.
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)
Shorter version:
but why used set object method, we can do it without set method ?
oh so new set is method which holds unique values