Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Levenshtein Distance in JavaScript
Levenshtein Distance
The Levenshtein distance is a string metric for measuring the difference between two sequences. It is the minimum number of single-character edits required to change one word into the other.
For example −
Consider, we have these two strings −
const str1 = 'hitting'; const str2 = 'kitten';
The Levenshtein distance between these two strings is 3 because we are required to make these three edits −
kitten → hitten (substitution of "h" for "k")
hitten → hittin (substitution of "i" for "e")
hittin → hitting (insertion of "g" at the end)
We are required to write a JavaScript function that takes in two strings and calculates the Levenshtein distance between them.
Example
Following is the code −
const str1 = 'hitting';
const str2 = 'kitten';
const levenshteinDistance = (str1 = '', str2 = '') => {
const track = Array(str2.length + 1).fill(null).map(() =>
Array(str1.length + 1).fill(null));
for (let i = 0; i Output
Following is the output on console −
3
Advertisements
