Searching for similar strings within an array or object map in Node.js

In this post we will see how can we search similar strings within the array of strings compared to input string.

We will using a npm package known as string-similarity.

String-similarity finds degree of similarity between two strings, based on Dice’s Coefficient

Using this package we will find the best matches from the array of multiple strings.

Install the npm package through node console as shown below:

>npm install string-similarity –save

Let us see how it works,


var stringSimilarity = require('string-similarity');

var inputString = "Log in";

var arrayofStrings = ["Sign in", "Log out", "Likes", "User Login", "thewebspark", "Admin Login"];

var matches = stringSimilarity.findBestMatch(inputString, arrayofStrings);

console.log(matches); //produces response with rating to each string

//initialize an empty array to store similar strings

var getSimilar = [];

for(var i in matches.ratings){

if(matches.ratings[i].rating > 0.2){

getSimilar.push(matches.ratings[i].target);

}

}

console.log("The similar strings for "+inputString+"are: \n" +getSimilar);

Below would be the output for the above code:

sim

 

Higher the rating score, better the match. Works nicely with lengthy strings also.

The things is we just have sort it out based on the score/ratings assigned to strings from the array. The rest is done by this API called string-similarity

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s