How to compare two string arrays, case insensitive and independent about ordering JavaScript, ES6

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a function, say isEqual() that takes in two strings as argument and checks if they both contains the same characters independent of their order and case.

For example −

const first = 'Aavsg';
const second = 'VSAAg';
isEqual(first, second); //true

Method: 1 Using arrays

In this method we convert the strings into arrays, make use of the Array.prototype.sort() method, convert them back into strings and check for equality.

The code for this will be −

Example

const first = 'Aavsg';
const second = 'VSAAg';
const stringSort = function(){
   return this.split("").sort().join("");
}
String.prototype.sort = stringSort;
const isEqual = (first, second) => first.toLowerCase().sort() ===
second.toLowerCase().sort();
console.log(isEqual(first, second));

Method 2: Using a Map

In this method we iterate over both the strings at the same time, store the character frequencies in a map with values like this −

-1, if it appears in the first string,
+1, if it appears in the second string,

At last, if all the keys add up 0, we conclude that that the strings are same otherwise not.

The code for this will be −

Example

const first = 'Aavsg';
const second = 'VSAAg';
const isEqual = (first, second) => {
   if(first.length !== second.length){
      return false;
   }
   first = first.toLowerCase();
   second = second.toLowerCase();
   const map = {};
   for(ind in first){
      if(map[first[ind]]){
         map[first[ind]]++;
      }else{
         map[first[ind]] = 1;
      }
      if(map[second[ind]]){
         map[second[ind]]--;
      }else{
         map[second[ind]] = -1;
      }
   };
   return Object.values(map).reduce((acc, val) => val === 0 && acc, true);
};
console.log(isEqual(first, second));

Output

The output in the console for both will be −

true
raja
Published on 20-Aug-2020 06:07:25
Advertisements