Removing consecutive duplicates from strings in an array using JavaScript


Problem

We are required to write a JavaScript function that takes in an array of strings. Our function should remove the duplicate characters that appear consecutively in the strings and return the new modified array of strings.

Example

Following is the code −

 Live Demo

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));

Output

[ 'keles', 'kenes' ]

Updated on: 20-Apr-2021

563 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements