js两个树形数组取交集
时间: 2024-04-10 19:23:35 浏览: 68
Java 程序查找两个数组之间的共同元素.docx
以下是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]
```
阅读全文