หากมีแค่สองอาร์เรย์ อาจใช้ตรรกะทั่วไปได้ แต่ถ้ามีหลายอาร์เรย์ จะซับซ้อนขึ้น เมธอด _.intersection() จาก underscore.js ช่วยให้ง่ายขึ้น โดยตรวจสอบทุกอิลิเมนต์และคืนค่าที่ซ้ำกันในทุกอาร์เรย์ หากมีอาร์เรย์ใดไม่มีค่าร่วมกัน จะได้ผลลัพธ์ว่าง
ไวยากรณ์
_.intersection(array1, array2, ...);
ตัวอย่าง
<html> <body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
<script type="text/javascript">
document.write(_.intersection([1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7, 8]));
</script> </body> </html>
ผลลัพธ์
1,2,3,4,5
รองรับค่า falsy เช่น null, undefined, void ด้วย
ตัวอย่างกับค่า falsy
<html> <body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
<script type="text/javascript">
document.write(_.intersection([1, 2, 3, "null", "undefined"], [1, 2, 3, "null", "undefined", "void"], [1, "null","void"]));
</script> </body> </html>
ผลลัพธ์
1,null