Computer >> Computer tutorials >  >> Programming >> Javascript

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 −

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' ]