JSFiddle - React, Tailwind, and code Playground
HTML
<h3> how similar are item_a and item_b </h3>
<div id="one"></div>
<h3> how similar are item_b and item_c </h3>
<div id="two"></div>
<h3> how similar are item_a and item_c </h3>
<div id="three"></div>
<h3> how similar are item_c and item_d </h3>
<div id="four"></div>
JavaScript
var item_a = {
'one': 1,
'two': 2
},
item_b = {
'one': 1,
'two': 2
},
item_c = {
'one': 1.5,
'two': 2.2,
'three': 3 //this is really important in c
},
item_d = {
'one': 1.2,
'two': 2.1,
'three': 2
};
function pad(a, b){
var a_fixed = {...a},
b_fixed = {...b};
for(const [key, val] of Object.entries(a)){
if(!b[key]){
b_fixed[key] = 0;
}
};
for(const [key, val] of Object.entries(b)){
if(!a[key]){
a_fixed[key] = 0;
}
};
return [a_fixed, b_fixed];
}
function norm(obj){
var norm = 0;
for(const [key, val] of Object.entries(obj)){
norm += val * val;
}
return Math.sqrt(norm);
}
function dotProduct(a, b){
var product = 0;
for(const [k, v] of Object.entries(a)){
product += v * b[k];
};
return product;
}
function getSimilarity(a, b){
var padded = pad(a, b),
dem = norm(padded[0]) * norm(padded[1]),
sim = dem != 0 ? dotProduct(padded[0], padded[1]) / dem : 0;
return sim;
}
document.getElementById('one').innerHTML = getSimilarity(item_a, item_b);
document.getElementById('two').innerHTML = getSimilarity(item_b, item_c);
document.getElementById('three').innerHTML = getSimilarity(item_a, item_c);
document.getElementById('four').innerHTML = getSimilarity(item_c, item_d);