การตรวจสอบว่า Array หนึ่งมี Elements ทั้งหมดจาก Array อีกตัวหนึ่งครบหรือไม่ ทำได้ด้วย every() ร่วมกับ includes() หรือใช้ Set สำหรับ Performance ดีกว่า
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Find by Multiple Values</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 18px; font-weight: 500; color: rebeccapurple; }
</style>
</head>
<body>
<h1>หา Elements ของ Array ด้วย Multiple Values</h1>
<div class="result"></div>
<button class="Btn">คลิกที่นี่</button>
<h3>คลิกปุ่มด้านบนเพื่อดูว่า arr มี elements ของ arr1 ครบหรือไม่</h3>
<script>
const BtnEle = document.querySelector(".Btn");
const resEle = document.querySelector(".result");
const arr = [11, 44, 22, 16, 25, 91, 58];
const arr1 = [22, 91, 11];
// every + includes: ตรวจสอบทุกตัวใน arr1 อยู่ใน arr
const containsAll = arr1.every(item => arr.includes(item));
BtnEle.addEventListener("click", () => {
if (containsAll) {
resEle.innerHTML = "arr มี elements ของ arr1 ครบทุกตัว";
} else {
resEle.innerHTML = "arr ไม่มี elements ของ arr1 ครบ";
}
});
</script>
</body>
</html>
วิธีการอื่นๆ และ Performance
| วิธี | Code | Time Complexity | เหมาะสำหรับ |
|---|---|---|---|
| every + includes | arr1.every(x => arr.includes(x)) | O(n×m) | Array เล็ก |
| Set + every | const s = new Set(arr); arr1.every(x => s.has(x)) | O(n+m) | Array ใหญ่ (แนะนำ) |
| filter + length | arr1.filter(x => arr.includes(x)).length === arr1.length | O(n×m) | ต้องการรายการที่เจอ |
| Set + filter | const s = new Set(arr); arr1.filter(x => s.has(x)) | O(n+m) | ต้องการรายการที่เจอ + Array ใหญ่ |
กรณีใช้งานอื่นๆ
// หา Intersection (ส่วนที่ซ้อนทับ)
const intersection = arr1.filter(x => arr.includes(x));
// หรือ
const set = new Set(arr);
const intersection = arr1.filter(x => set.has(x));
// หา Difference (อยู่ใน arr1 แต่ไม่อยู่ใน arr)
const difference = arr1.filter(x => !arr.includes(x));
// ตรวจสอบ Any (มีอย่างน้อย 1 ตัว)
const hasAny = arr1.some(x => arr.includes(x));
ผลลัพธ์
arr มี elements ของ arr1 ครบทุกตัว (22, 91, 11 อยู่ใน arr ทั้งหมด)