如何比较两个字符串数组,不区分大小写,也不依赖于顺序 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

更新于:20-Aug-2020

686 次浏览

开启你的 职业生涯

完成课程后获得认证

开始
广告
© . All rights reserved.