Skip to content

Instantly share code, notes, and snippets.

@rloredo
Last active September 26, 2021 11:51
Show Gist options
  • Save rloredo/8acd3f0152e4663737d44312bea4c3ad to your computer and use it in GitHub Desktop.
Save rloredo/8acd3f0152e4663737d44312bea4c3ad to your computer and use it in GitHub Desktop.
Calculate cosine similarity in javascript
function cosinesim(A,B){
var dotproduct=0;
var mA=0;
var mB=0;
for(i = 0; i < A.length; i++){
dotproduct += (A[i] * B[i]);
mA += (A[i]*A[i]);
mB += (B[i]*B[i]);
}
mA = Math.sqrt(mA);
mB = Math.sqrt(mB);
var similarity = (dotproduct)/((mA)*(mB))
return similarity;
}
var array1 = [1,1,0,0,0,0,0,0,0,0];
var array2 = [1,0,1,1,1,1,1,1,1,1];
var p = cosinesim(array1,array2);
console.log(p);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment