题目链接:https://leetcode-cn.com/problems/intersection-of-two-arrays/
使用set求2个数组的交集:
var intersection = function(nums1, nums2) {
var set = new Set(nums1)
//Array.from 就是将一个类数组对象或者可遍历对象转换成一个真正的数组
nums2 = Array.from(new Set(nums2)) //为nums2去重
return nums2.filter(num => set.has(num)); //保留nums1里面共有的 set.has(num)
};
var intersection = function(nums1, nums2) {
let result = [...new Set(nums2)].filter(item => new Set(nums1).has(item));
return result;
};
引申:
求2个数组的并集:
let result = [...new Set([...nums1,...nums2])];
求2个数组的差集:
let result = [...new Set(nums1)].filter(item => !(new Set(nums2).has(item)));