Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

So sánh hai đối tượng JavaScript trả về phần trăm tương đồng

Cho hai đối tượng, viết hàm đếm số thuộc tính chung (cùng key và value) và trả về phần trăm tương đồng 0-100. Phần trăm = (số thuộc tính chung / số thuộc tính object nhỏ hơn) * 100.

Ví dụ

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));

Kết quả

Đầu ra trong console sẽ là:

66.66666666666666

Vì object nhỏ hơn có 3 thuộc tính, 2 thuộc tính chung → ~66%.