假设我们有两个这样的对象-
const a = {
Make: "Apple",
Model: "iPad",
hasScreen: "yes",
Review: "很棒的产品!",
};
const b = {
Make: "Apple",
Model: "iPad",
waterResistant: false
};我们需要编写一个函数来计算对象中共有属性的数量(通过共有属性,我们指的是键和值都相同),并返回介于0和100之间(包括两端)的数字,该数字表示对象之间相似度的百分比对象。就像没有键/值对匹配时为0,如果所有匹配都为100。
要计算相似性百分比,我们可以简单地将相似属性的计数除以较小对象(一个键/值对较少的对象)中的属性数量,然后将该结果乘以100。
因此,了解了这一点之后,现在让我们编写该函数的代码-
const a = {
Make: "Apple",
Model: "iPad",
hasScreen: "yes",
Review: "很棒的产品!",
};
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%。