在 JavaScript 中比较两个对象并返回一个介于 0 和 100 之间的数字,表示相似度百分比

javascriptweb developmentobject oriented programming更新于 2025/10/22 1:48:17

假设我们有两个像这样的对象 −

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

我们需要编写一个函数来计算对象中公共属性的数量(公共属性指的是键和值都相同),并返回一个介于 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%。


相关文章


有用资源