過濾字串以在 JavaScript 中包含唯一字元


問題

我們需要編寫一個 JavaScript 函式來獲取字串 str。我們的函式應該構造一個新字串,該字串僅包含輸入字串中的唯一字元,並刪除所有重複字元。

示例

以下是程式碼 -

 即時演示

const str = 'hey there i am using javascript';
const removeAllDuplicates = (str = '') => {
   let res = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(str.indexOf(el) === str.lastIndexOf(el)){
         res += el;
         continue;
      };
   };
   return res;
};
console.log(removeAllDuplicates(str));

輸出

以下是控制檯輸出 -

Ymungjvcp

更新時間: 2021 年 4 月 17 日

673 次瀏覽

開啟您的事業

完成課程獲得認證

開始
廣告