使用 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 次查看

开启您的 职业之旅

完成课程以获得认证

开始
广告
© . All rights reserved.