Search code examples
javascriptnode.jscosine-similarity

Node.js cosine similarity between array and object array


How can I find the similarity using node.js between an array vector x with 4 elements and an array of objects y?

var similarity = require( 'compute-cosine-similarity' );

var y= [ {'1': [30,12,0,3]},
         {'2':[30,12,0,6]},
         {'3':[30,12,0,1000]} ];

var x =[2,2,2,2];

s=similarity(x, y);

console.log(s);

for example the first iteration should find the similarity between

x = [2,2,2,2]

and

{'1': [30,12,0,3]}

and so on..


Solution

  • you can run this code :

    var similarity = require( 'compute-cosine-similarity' );
    
    var y= [ {'1': [30,12,0,3]},
      {'2':[30,12,0,6]},
      {'3':[30,12,0,1000]} ];
    
    var x =[2,2,2,2];
    var result=[];
    for(var i=0;i<y.length;i++){
      for (var key in y[i]) {
        if (y[i].hasOwnProperty(key)) {
    
          result.push(similarity(x, y[i][key]))
        }
      }
    }
    console.log(result);// will print the similarity as an array [ 0.6933752452815364, 0.7302967433402213, 0.5207282507611518 ]
    

    if you need an other output leave a comment thanks !