示例 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]
在上面的程序中,在
使用 array1
和
array2
之间进行了交集。
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))