JavaScript 执行两个数组之间的交集程序

要理解此示例,您应了解以下 JavaScript 编程 主题


示例 1:使用 Set 执行交集

// program to perform intersection between two arrays using Set
// intersection contains the elements of array1 that are also in array2

function performIntersection(arr1, arr2) {

    // converting into Set
    const setA = new Set(arr1);
    const setB = new Set(arr2);

    let intersectionResult = [];

    for (let i of setB) {
    
        if (setA.has(i)) {
            intersectionResult.push(i);
        }
        
    }
    
    return intersectionResult;

}

const array1 = [1, 2, 3, 5, 9];
const array2 = [1, 3, 5, 8];

const result = performIntersection(array1, array2);
console.log(result);

输出

[1, 3, 5]

在上面的程序中,对 array1array2 之间执行了交集。

  • 使用 new Set() 构造函数将数组元素转换为 Set 元素。
  • 使用 for...of 循环遍历第二个 Set 元素。
  • 使用 has() 方法检查该元素是否存在于第一个 Set 中。
  • 如果元素存在于第一个 Set 中,则使用 push() 方法将该元素添加到 intersectionResult 数组中。

示例 2:使用 filter() 方法执行交集

// program to perform intersection between two arrays

function performIntersection(arr1, arr2) {

    const intersectionResult = arr1.filter(x => arr2.indexOf(x) !== -1);
 
    return intersectionResult;

}

const array1 = [1, 2, 3, 5, 9];
const array2 = [1, 3, 5, 8];

const result = performIntersection(array1, array2);
console.log(result);

输出

[1, 3, 5]

在上面的程序中,使用 filter() 方法对两个数组之间的交集进行了计算。filter 方法会遍历一个数组并返回通过给定条件的数组元素。

  • 使用 indexOf() 方法将第一个数组的每个元素与第二个数组进行比较。
  • arr2.indexOf(x) 方法会在 arr2 中搜索 arr1 的第一次出现,并返回其位置。如果找不到该值,则返回 -1
  • filter() 方法返回所有同时存在于两个数组中的元素。

注意:您也可以使用 includes() 方法来检查数组元素是否同时存在于两个数组中。

const intersectionResult = arr1.filter(x => arr2.includes(x))

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战