- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Removing adjacent duplicates from a string in JavaScript
Problem
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.
Example
The code for this will be −
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){ arr.pop(); }; } else { arr.push(char); }; }; return arr.join(''); }; console.log(removeDuplicates(str));
Output
And the output in the console will be −
mk
- Related Articles
- Removing duplicates from a sorted array of literals in JavaScript
- Removing consecutive duplicates from strings in an array using JavaScript
- Removing duplicates from tuple in Python
- Remove All Adjacent Duplicates In String in Python
- Removing punctuations from a string using JavaScript
- Removing a specific substring from a string in JavaScript
- Remove All Adjacent Duplicates in String II in C++
- Removing duplicates and inserting empty strings in JavaScript
- Removing duplicates and keep one instance in JavaScript
- Removing all spaces from a string using JavaScript
- Removing first k characters from string in JavaScript
- Removing comments from array of string in JavaScript
- Print a closest string that does not contain adjacent duplicates in C++
- Removing all non-alphabetic characters from a string in JavaScript
- Removing n characters from a string in alphabetical order in JavaScript

Advertisements