比較 JavaScript 中的兩個物件,並返回一個介於 0 到 100 之間的數字,表示相似度百分比。


假設我們有兩個這樣的物件:

const a = {
   Make: "Apple",
   Model: "iPad",
   hasScreen: "yes",
   Review: "Great product!",
};
const b = {
   Make: "Apple",
   Model: "iPad",
   waterResistant: false
};

我們需要編寫一個函式,計算物件中共有屬性的數量(共有屬性指鍵和值都相同),並返回一個介於 0 到 100(包含 0 和 100)之間的數字,表示物件之間的相似度百分比。例如,如果沒有任何鍵/值對匹配,則為 0;如果全部匹配,則為 100。

為了計算相似度百分比,我們可以簡單地將相似屬性的數量除以較小物件中的屬性數量(鍵/值對較少的那個),並將結果乘以 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 個屬性,其中 2 個是共有的,大約佔 66%。

更新於: 2020-08-28

459 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.