Skip to content

getIntersection

取两个数组的交集并去重

配置项

参数类型是否必选默认值参数描述
array1Array-参数1
array2Array-参数2

返回值

类型描述
Array两者的交集数组

示例

getIntersection([1], [1, 1, 2]) // [1]
getIntersection([1], [2]) // []

源码

js
export function getIntersection(array1, array2) {// 检查输入的 array 是否为数组
    if (!Array.isArray(array1) || !Array.isArray(array2)) {
        throw new Error('参数必须是数组');
    }

    // 检查输入的数组是否为空数组
    if (array1.length === 0 || array2.length === 0) {
        return [];
    }
    const set = new Set(array2);
    const intersection = array1.filter((value) => set.has(value));
    return Array.from(new Set(intersection));
}