How to use Index Comparison In Javascript

In this approach, we utilize an iterative loop and compare characters using their indices to identify consecutive duplicate characters. We iterate through the string and compare each character with the next character. If they are different, we append the current character to the output string. This approach does not rely on an additional data structure.

Example:

JavaScript
function removeConsecutiveDuplicates(inputData) {
    let output = "";
    for (let i = 0; i < inputData.length; i++) {
        // If current character is not the same as next character
        if (inputData[i] !== inputData[i + 1]) {
            output += inputData[i];
        }
    }
    return output;
}

const testString = "Geeks For Geeks";
console.log(removeConsecutiveDuplicates(testString));

Output
Geks For Geks




JavaScript Program to Remove Consecutive Duplicate Characters From a String

In this article, we are going to implement a JavaScript program to remove consecutive duplicate characters from a string. In this program, we will eliminate all the consecutive occurrences of the same character from a string.

Example:

Input: string: "geeks" 
Output: "geks"
Explanation :consecutive "e" should be removed

Table of Content

  • Using Iterative Loop
  • Using Regular Expressions
  • Using Array Methods
  • Using Index Comparison

Similar Reads

Using Iterative Loop

In this approach, we are using the for loop and if else statement to check if the current letter is the same as the last character or not. If it is, then we are skipping it, and if not, we are adding that character to the output string....

Using Regular Expressions

In this approach, we are traversing each character of the string and checking if it is the same as the last character or not using the replace method. If it is the same, then we skip it; otherwise, we return it....

Using Array Methods

Using array methods to remove consecutive duplicate characters involves splitting the string into an array of characters, filtering out characters that are equal to their next character, then joining the filtered array back into a string....

Using Index Comparison

In this approach, we utilize an iterative loop and compare characters using their indices to identify consecutive duplicate characters. We iterate through the string and compare each character with the next character. If they are different, we append the current character to the output string. This approach does not rely on an additional data structure....