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
-
Economics & Finance
How to compare two string arrays, case insensitive and independent about ordering JavaScript, ES6
We need to write a function that compares two strings to check if they contain the same characters, ignoring case and order. This is useful for validating anagrams or checking string equivalence.
For example:
const first = 'Aavsg'; const second = 'VSAAg'; isEqual(first, second); // true
Using Array Sort Method
This method converts strings to arrays, sorts the characters, and compares the results. We extend the String prototype to add a sort method.
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));
true
Using Character Frequency Map
This method counts character frequencies using a Map. Characters from the first string get +1, characters from the second string get -1. If all values sum to 0, the strings are equivalent.
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(let ind = 0; ind val === 0);
};
console.log(isEqual(first, second));
true
Using ES6 Map for Cleaner Code
Here's a more modern approach using ES6 Map and for...of loops:
const first = 'Aavsg';
const second = 'VSAAg';
const isEqual = (str1, str2) => {
if (str1.length !== str2.length) return false;
const charCount = new Map();
// Count characters in first string
for (const char of str1.toLowerCase()) {
charCount.set(char, (charCount.get(char) || 0) + 1);
}
// Subtract characters from second string
for (const char of str2.toLowerCase()) {
if (!charCount.has(char)) return false;
charCount.set(char, charCount.get(char) - 1);
}
// Check if all counts are zero
return [...charCount.values()].every(count => count === 0);
};
console.log(isEqual(first, second));
true
Comparison of Methods
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Array Sort | O(n log n) | O(n) | High |
| Character Map | O(n) | O(k) where k = unique chars | Medium |
| ES6 Map | O(n) | O(k) where k = unique chars | High |
Conclusion
The Map-based approaches offer better time complexity O(n) compared to sorting O(n log n). Use the ES6 Map method for optimal performance and clean, readable code.
