 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Hamming Distance between two strings in JavaScript
Hamming Distance
The Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.
For example, consider the following strings −
const str1 = 'delhi'; const str2 = 'delph';
The Hamming Distance of these strings is 2 because the fourth and the fifth characters of the strings are different. And obviously in order to calculate the Hamming Distance we need to have two strings of equal lengths.
Therefore, we are required to write a JavaScript function that takes in two strings, let’s say str1 and str2, and returns their hamming distance.
Example
Following is the code −
const str1 = 'delhi'; const str2 = 'delph'; const hammingDistance = (str1 = '', str2 = '') => {    if (str1.length !== str2.length) {       return 0;    }    let dist = 0;    for (let i = 0; i < str1.length; i += 1) {       if (str1[i] !== str2[i]) {          dist += 1;       };    };    return dist; }; console.log(hammingDistance(str1, str2)); Output
Following is the output on console −
2
Advertisements
 