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

Example 1:

Input: nums1 =,2,2,1 [1], nums2 = (2, 2] output: [2] example 2:

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

The number of occurrences of each element in the output should be the same as the number of occurrences of the element in both arrays. We can ignore the order of the output.

/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */
var intersect = function(nums1, nums2) {
    let arr = []
    for (let i = 0; i<nums1.length; i++){let j = nums2.indexOf(nums1[i])
        if(j>=0){
            arr.push(nums1[i])
            nums2.splice(j,1)}}return arr
};
Copy the code