Removing adjacent duplicates from a string in JavaScript


JavaScript function that takes in a string, str, as the first and the only argument.

A duplicate removal consists of choosing two adjacent and equal letters, and removing them.

We repeatedly make duplicate removals on string str until we no longer can.

And our function should finally return the final string after all such duplicate removals have been made.

For example, if the input to the function is −

const str = 'kllkmk';

Then the output should be −

const output = 'mk';

Output Explanation:

Firstly, we will remove ‘ll’ from the string to reduce it to ‘kkmk’, then after removing ‘kk’, we will return the new string.


The code for this will be −

 Live Demo

const str = 'kllkmk';
const removeDuplicates = (str = '') => {
   const arr = [];
   for(const char of str){
      if(char === arr[arr.length - 1]){
         while(arr[arr.length - 1] === char){
      } else {
   return arr.join('');  


And the output in the console will be −