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
345 views
in Technique[技术] by (71.8m points)

javascript - JavaScript中数组交集的最简单代码(Simplest code for array intersection in javascript)

What's the simplest, library-free code for implementing array intersections in javascript?(在javascript中实现数组交集的最简单,无库代码是什么?)

I want to write(我想写) intersection([1,2,3], [2,3,4,5]) and get(并得到) [2, 3]   ask by Peter translate from so

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

1 Answer

0 votes
by (71.8m points)

Use a combination of Array.prototype.filter and Array.prototype.indexOf :(结合使用Array.prototype.filterArray.prototype.indexOf :)

array1.filter(value => -1 !== array2.indexOf(value)) Or as vrugtehagel suggested in the comments, you can use the more recent Array.prototype.includes for even simpler code:(或如评论中建议的vrugtehagel一样 ,您可以使用更新的Array.prototype.includes来获取更简单的代码:) array1.filter(value => array2.includes(value)) For older browsers:(对于较旧的浏览器:) array1.filter(function(n) { return array2.indexOf(n) !== -1; });

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

...