intersection of two arrays code example

Example 1: javascript get intersection of two arrays

function getArraysIntersection(a1,a2){
    return  a1.filter(function(n) { return a2.indexOf(n) !== -1;});
}
var colors1 = ["red","blue","green"];
var colors2 = ["red","yellow","blue"];
var intersectingColors=getArraysIntersection(colors1, colors2); //["red", "blue"]

Example 2: can we calculate the intersection of duplicate ele

from collections import Counter

c = list((Counter(a) & Counter(b)).elements())

Example 3: intersection of two arrays

def intersection(nums1 , nums2):
    result =  []
    memo = {}

    for currentVal in nums1:

        if currentVal in memo: 
            memo[currentVal] += 1

        else:
            memo[currentVal] = 1
    
    for currentVal in nums2:

            if currentVal in memo:
                result.append(currentVal)

                memo[currentVal] -= 1

                if memo[currentVal] == 0:
                    del memo[currentVal]

    return result

nums1 = [10, 10, 25, 14, 14, 14, 56]
nums2 = [10, 10, 14, 23, 34, 56]

print(intersection(nums1, nums2))