如何比較兩個字串陣列,不區分大小寫,也不依賴於順序 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.