บทความนี้สาธิตวิธีหาค่าที่ซ้ำกัน (common elements) ในทุกอาร์เรย์ที่อยู่ภายในออบเจกต์ โดยจำนวนอาร์เรย์ไม่คงที่
ตัวอย่างข้อมูล
const obj = {
a: [15, 23, 36, 49, 104, 211],
b: [9, 12, 23],
c: [11, 17, 18, 23, 38],
d: [13, 21, 23, 27, 40, 85]
};
ตัวอย่างโค้ด
const obj = {
a: [15, 23, 36, 49, 104, 211],
b: [9, 12, 23],
c: [11, 17, 18, 23, 38],
d: [13, 21, 23, 27, 40, 85]
};
const commonBetweenTwo = (arr1, arr2) => {
const res = [];
for (let i = 0; i < arr1.length; i++) {
if (arr2.includes(arr1[i])) {
res.push(arr1[i]);
}
}
return res;
};
const commonBetweenMany = (obj = {}) => {
const keys = Object.keys(obj);
let res = obj[keys[0]];
for (let i = 1; i < keys.length; i++) {
res = commonBetweenTwo(res, obj[keys[i]]);
if (!res.length) {
return [];
}
}
return res;
};
console.log(commonBetweenMany(obj));
ผลลัพธ์
[23]
คำอธิบาย
ฟังก์ชัน commonBetweenTwo หาค่าที่ซ้ำระหว่าง 2 อาร์เรย์
ฟังก์ชัน commonBetweenMany ใช้คีย์ของออบเจกต์ วนลูปหาค่าซ้ำสะสมทีละอาร์เรย์ เริ่มจากอาร์เรย์แรก หากในขั้นไหนผลลัพธ์ว่างเปล่า คืนค่า [] ทันที