0

I have a set of strings that look like this,

{0:{question:"1f31f", answer:"1f31a"},1:{question:"1f32f", answer:"1fada"}}

I'm trying to use Javascript to show the percentage similarity between these strong strings - wondering if there's a simple way to do this?

Based on the index of the string, how many are correctly positioned.

Alexander van Oostenrijk
  • 4,644
  • 3
  • 23
  • 37
LeCoda
  • 538
  • 7
  • 36
  • 79

2 Answers2

2

If the strings are always of the same length, consider calculating their Hamming distance. If they are not always of the same length, look into the Levenshtein distance.

Alexander van Oostenrijk
  • 4,644
  • 3
  • 23
  • 37
2

Since I don't know how complex you want your answer to be and others already provided some great methods, I figured I just submit the most simple, plain answer since sometimes that is all you need. Just comparing how many indices are the same:

let s1 = "1f31f";
let s2 = "1f31a"
let s3 = "1fada";

compare(s1, s2);
compare(s1, s3);

function compare(s1, s2) {
  let correct = 0;
  for (let i = 0; i < s1.length; i++) {
    if (s1.charAt(i) == s2.charAt(i)) {
      correct += 1;
    }
  }

  console.log(((correct / s1.length) * 100) + "%");
}
bluejambo
  • 221
  • 1
  • 11