สมมติว่าเรามีสองอ็อบเจกต์แบบนี้:
const a = {
Make: "Apple",
Model: "iPad",
hasScreen: "yes",
Review: "Great product!"
};
const b = {
Make: "Apple",
Model: "iPad",
waterResistant: false
};
เราต้องเขียนฟังก์ชันที่นับจำนวน property ที่เหมือนกันในอ็อบเจกต์ (property เหมือนกันหมายถึง key และ value เหมือนกันทั้งคู่) และคืนค่าตัวเลข 0-100 (รวมทั้งสองข้าง) ที่แทนเปอร์เซ็นต์ความคล้ายคลึงระหว่างอ็อบเจกต์ เช่น ถ้าไม่มี key/value คู่ไหนตรง จะเป็น 0 ถ้าทุกคู่ตรงจะเป็น 100
เพื่อคำนวณเปอร์เซ็นต์ความคล้ายคลึง เราสามารถหารจำนวน property ที่คล้ายกันด้วยจำนวน property ในอ็อบเจกต์ที่เล็กกว่า (อันที่มี key/value น้อยกว่า) และคูณผลลัพธ์ด้วย 100
ตอนนี้เข้าใจแล้ว มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน:
ตัวอย่างโค้ด
const a = {
Make: "Apple",
Model: "iPad",
hasScreen: "yes",
Review: "Great product!"
};
const b = {
Make: "Apple",
Model: "iPad",
waterResistant: false
};
const findSimilarity = (first, second) => {
const firstLength = Object.keys(first).length;
const secondLength = Object.keys(second).length;
const smaller = firstLength < secondLength ? first : second;
const greater = smaller === first ? second : first;
const count = Object.keys(smaller).reduce((acc, val) => {
if (Object.keys(greater).includes(val)) {
if (greater[val] === smaller[val]) {
return ++acc;
}
}
return acc;
}, 0);
return (count / Math.min(firstLength, secondLength)) * 100;
};
console.log(findSimilarity(a, b));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้:
66.66666666666666
เพราะอ็อบเจกต์ที่เล็กกว่ามี 3 property ซึ่ง 2 ตัวตรงกัน ประมาณ 66%