使用 JavaScript 從陣列中的字串中刪除連續重複項


問題

我們要求編寫一個 JavaScript 函式,它接受一個字串陣列。我們的函式應該刪除字串中連續出現的重複字元,並返回修改後的新字串陣列。

示例

以下為程式碼 -

 即時演示

const arr = ["kelless", "keenness"];
const removeConsecutiveDuplicates = (arr = []) => {
   const map = [];
   const res = [];
   arr.map(el => {
      el.split('').reduce((acc, value, index, arr) => {
         if (arr[index] !== arr[index+1]) {
            map.push(arr[index]);
         }
         if (index === arr.length-1) {
            res.push(map.join(''));
            map.length = 0
         }
      }, 0);
   });
   return res;
}
console.log(removeConsecutiveDuplicates(arr));

輸出

[ 'keles', 'kenes' ]

更新於: 2021 年 4 月 20 日

772 次檢視

開啟您的 職業之旅

完成課程以獲得認證

開始
廣告