Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

js怎么判断两数组之间有没有交集

有两个数组:数组1和数组2;
想实现的需求:判断数组2里有没有数组1的任意一项,有则true,无则false

let arr1 = [1,2,3,4,5,6];
let arr2 = [6,7,8,9,10,11];
let result = false;
for(item of arr1){
    if(arr2.includes(item)){
        result = true;
        break;
    }
}

有没有大佬有更好的写法


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

var arr1 = [1,2,3,4,5,6];
var arr2 = [6,7,8,9,10,11];
var result = (arr1.length + arr2.length) !== Array.from(new Set([...arr1,...arr2])).length;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...