js两个树形数组取交集
时间: 2024-04-10 13:23:35 浏览: 25
以下是JavaScript获取两个数组交集的方法:
方法一:使用filter()和includes()方法
```javascript
function getIntersection(arr1, arr2) {
return arr1.filter(item => arr2.includes(item));
}
// 示例用法
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [4, 5, 6, 7, 8];
const intersection = getIntersection(arr1, arr2);
console.log(intersection); // 输出:[4, 5]
```
方法二:使用Set对象
```javascript
function getIntersection(arr1, arr2) {
const set1 = new Set(arr1);
const set2 = new Set(arr2);
return Array.from(new Set([...set1].filter(item => set2.has(item))));
}
// 示例用法
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [4, 5, 6, 7, 8];
const intersection = getIntersection(arr1, arr2);
console.log(intersection); // 输出:[4, 5]
```
相关问题
js两个对象数组取交集
你可以使用 `filter` 方法结合 `indexOf` 函数来实现两个对象数组的交集。
假设有两个对象数组 `arr1` 和 `arr2`,你可以按照以下方式实现它们的交集:
```javascript
const arr1 = [{id: 1}, {id: 2}, {id: 3}];
const arr2 = [{id: 2}, {id: 3}, {id: 4}];
const intersection = arr1.filter(item1 => arr2.some(item2 => item2.id === item1.id));
console.log(intersection); // [{id: 2}, {id: 3}]
```
在上面的例子中,`filter` 方法遍历了 `arr1` 数组中的每一个元素,对于每一个元素都使用 `some` 方法在 `arr2` 数组中查找是否存在相同 `id` 值的对象。如果存在,则保留该元素,否则过滤掉该元素。最终,`intersection` 数组保存了两个数组的交集。
vba 两个数组取交集
以下是VBA代码示例,用于计算两个数组的交集:
Sub Intersection()
Dim arr1() As Variant
Dim arr2() As Variant
Dim arr3() As Variant
arr1 = Array(1, 2, 3, 4, 5)
arr2 = Array(3, 4, 5, 6, 7)
For i = LBound(arr1) To UBound(arr1)
For j = LBound(arr2) To UBound(arr2)
If arr1(i) = arr2(j) Then
ReDim Preserve arr3(UBound(arr3) + 1)
arr3(UBound(arr3)) = arr1(i)
Exit For
End If
Next j
Next i
For k = LBound(arr3) To UBound(arr3)
Debug.Print arr3(k)
Next k
End Sub
在此示例中,我们使用三个变量arr1,arr2和arr3。arr1和arr2是要比较的两个数组,arr3将包含它们的交集。我们使用两个嵌套的For循环来比较arr1和arr2中的每个元素。如果它们相等,我们将该元素添加到arr3中。最后,我们使用另一个循环打印arr3中的所有元素。
请注意,此示例假定arr3是空的数组。如果arr3包含任何元素,您需要在添加新元素之前使用ReDim保留数组的大小。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)