Skip to content

Instantly share code, notes, and snippets.

@SethVandebrooke
Created July 9, 2021 20:08
Show Gist options
  • Save SethVandebrooke/fbb1f83fc60707d72cfd2af9c990123d to your computer and use it in GitHub Desktop.
Save SethVandebrooke/fbb1f83fc60707d72cfd2af9c990123d to your computer and use it in GitHub Desktop.
Get the percentage of similar words between two texts. This function returns a score from 0 to 100 and an array of words in common between the two.
function similarity(text1, text2) {
text1 = text1.split(/\s+/);
text2 = text2.split(/\s+/);
let wordsInCommon = [];
let similarWordCount = 0;
for (var i = 0; i < text1.length; i++) {
let word = text1[i];
if (text2.includes(word)) {
similarWordCount++;
if (!wordsInCommon.includes(word)) {
wordsInCommon.push(word);
}
}
}
for (var i = 0; i < text2.length; i++) {
let word = text2[i];
if (text1.includes(word)) {
similarWordCount++;
if (!wordsInCommon.includes(word)) {
wordsInCommon.push(word);
}
}
}
return {
score: Math.floor(similarWordCount / (text1.length + text2.length) * 100),
wordsInCommon
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment