# Compare two objects in JavaScript and return a number between 0 and 100 representing the percentage of similarity

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we have two objects like these −

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

We are required to write a function that counts the number of common properties in the objects (by common property we mean having both key and value same) and returns a number between 0 and 100 (both inclusive) that represents the percentage of similarity between the objects. Like if no key/value pair matches it will be 0, if all matches it will be 100.

To count the percentage of similarity we can simply divide the count of similar property by the number of properties in the smaller object (one that have lesser key/value pairs) and multiply this result by 100.

So, with that understood, now let’s write the code for this function −

## Example

const a = {
Make: "Apple",
hasScreen: "yes",
Review: "Great product!",
};
const b = {
Make: "Apple",
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));

## Output

The output in the console will be −

66.66666666666666

Because the smaller object has 3 properties of which 2 are common which amount to approximately 66%.