如何比较两个不区分大小写并且与订购JavaScript,ES6无关的字符串数组
我们需要编写一个函数,说它isEqual()接受两个字符串作为参数,并检查它们是否都包含相同的字符,而与它们的顺序和大小写无关。
例如-
const first = 'Aavsg'; const second = 'VSAAg'; isEqual(first, second); //true
方法:1使用数组
在此方法中,我们将字符串转换为数组,利用Array.prototype.sort()方法,将其转换回字符串并检查是否相等。
为此的代码将是-
示例
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));方法2:使用映射
在这种方法中,我们同时迭代两个字符串,将字符频率存储在映射中,其值如下所示:
-1, if it appears in the first string, +1, if it appears in the second string,
最后,如果所有键的总和为0,我们得出的结论是字符串相同,否则相同。
为此的代码将是-
示例
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));输出结果
两者在控制台中的输出将是-
true