บทความนี้สาธิตการหาค่าที่ซ้ำกันระหว่าง 2 อาร์เรย์ โดยนับจำนวนครั้งที่ซ้ำด้วย (multiset intersection)
ตัวอย่าง
arr1 = [1, 2, 2, 4, 4, 5, 6] arr2 = [3, 2, 4, 2, 4, 9] // output: [2, 2, 4, 4]
ตัวอย่างโค้ด
const arr1 = [1, 2, 2, 4, 4, 5, 6];
const arr2 = [3, 2, 4, 2, 4, 9];
const findIntersection = (arr1 = [], arr2 = []) => {
const map = new Map();
for (const el of arr2) {
const count = map.get(el) || 0;
map.set(el, count + 1);
}
return arr1.filter(el => {
let count = map.get(el);
if (count) {
map.set(el, --count);
return true;
}
return false;
});
};
console.log(findIntersection(arr1, arr2));
ผลลัพธ์
[2, 2, 4, 4]
คำอธิบาย
สร้าง Map นับความถี่ของ arr2 แล้ว filter arr1: หากพบใน map และ count > 0 ให้ลด count ลง 1 และ keep element นั้น
วิธีนี้รักษาลำดับของ arr1 และจัดการ duplicate ถูกต้อง