ใช้ filter() ร่วมกับ includes() หา intersection
กรองอาร์เรย์แรก เฉพาะค่าที่มีอยู่ในอาร์เรย์ที่สองด้วย
ตัวอย่างโค้ด
var firstNamesArray = ["John", "David", "Bob", "Sam", "Carol"];
var secondNamesArray = ["Mike", "Carol", "Adam", "David"];
var intersectionOfArray = firstNamesArray.filter(v => secondNamesArray.includes(v));
console.log("Intersection of two arrays = ");
console.log(intersectionOfArray); // ["David", "Carol"]
วิธีรัน
node fileName.js
ผลลัพธ์
Intersection of two arrays = [ 'David', 'Carol' ]
คำอธิบาย
filter()สร้างอาร์เรย์ใหม่จาก element ที่ผ่านเงื่อนไขincludes()ตรวจสอบว่าค่าอยู่ในอาร์เรย์หรือไม่- Time Complexity: O(n×m) - เหมาะกับอาร์เรย์ขนาดเล็ก-ปานกลาง
เพิ่มประสิทธิภาพด้วย Set (สำหรับอาร์เรย์ใหญ่)
const set2 = new Set(secondNamesArray);
const intersection = firstNamesArray.filter(v => set2.has(v));
// O(n + m) เร็วกว่ามากสำหรับข้อมูลเยอะ
ลบค่าซ้ำในผลลัพธ์ (Unique Intersection)
[...new Set(intersectionOfArray)];