Compare two strings using javascript (nodejs) get uncommon characters count

Hafiz Hussain
2 min readJun 1, 2022

Sample input

string1 = “Joe”

string2 = “John”

Expected output is 3

Explanation of the output

From string1 = 1 letter, “e” is uncommon and from string2 = 2 letters “ h and n” are uncommon characters with the other string.

The solution looks obvious, but I didn’t find any straight forward method on internet to do so. I found some solution on geeksforgeeks website, but it was for c++.

So I thought to write the algorithm on javascript, hope it is helpful to some.

let the code begin

let a = ‘joe’, b = ‘john’; // giving two different string

// This function will generate an object that has number of occurrences of each letter for a given word

function getAlphabetsCount(arr) {
return arr.split(‘’).reduce((x, y) => {
x[y] = x[y] ? x[y] : 0;
x[y] += 1;

return x;

}, {})

I will call the above method with both the strings.

The first string will give the result as {‘j’ : 1, ‘o’:1, ‘e’:1}

The second string will give the result as {‘j’ : 1, ‘o’:1, ‘h’:1, ’n’ : 1}

let adata = getAlphabetsCount(a);
let bdata = getAlphabetsCount(b);

Now that I know, which alphabet has how many occurrences, I just need to iterate with each alphabet and check the difference of number of occurrences of both the strings.

let atoZ = “abcdefghijklmnopqrstuvwxyz”.split(‘’);

let count = 0;
for(let i =0; i< atoZ.length;i++) {

let letter = atoZ[i];

bdata[letter] = bdata[letter] ? bdata[letter] : 0;
adata[letter] = adata[letter] ? adata[letter] : 0;

// Once I get the difference, I take the absolute value of the difference and count it iteratively to give the total number of uncommon characters.
count += Math.abs(adata[letter] — bdata[letter]);


The final value will give the total count of uncommon characters.

This code can be modified slightly to get uncommon alphabets also.

Adding the JsFiddle here to play with the code.