Looking to remove repeated consecutive characters in a string with JavaScript?

In a Codewars challenge, I have to create a function that takes a string and returns an array without consecutive identical elements while maintaining the original order.

For example, if the input is "hhhhheeeelllloooooohhheeeyyy", the function should output ["h","e","l","o","h","e","y"].

This is the code I came up with:

var uniqueInOrder=function(iterable){
  var unique = [];
  for(var i = 0; i < iterable.length; i++) {
    unique.push(iterable[i]);
  } 

  for(var j = 0, k = 1; j < unique.length; j++, k = j + 1) {
    if(unique[j] === unique[k]) {
      unique.splice(k, 1);
    }
  }
  return unique;
}

However, when I test it with a string like "hhhhheeeeeellllloooo", it fails because the value of j keeps incrementing, preventing all identical elements from being filtered out.

I attempted modifying the logic so that if unique[j] === unique[k], the value of j resets to zero. But this resulted in an infinite loop instead.

I'm struggling to fix this issue and would appreciate any help you can offer.

Answer №1

The issue with the second for loop is that unique.length is not constant throughout its execution. I propose a solution to your problem:

var temp = iterable[0];
unique.push(iterable[0]);
for( var i = 1; i < iterable.length; i++) {
   if(iterable[i] != temp) {
       unique.push(iterable[i]);
       temp = iterable[i];
   }
} 

I hope this resolves your problem!

Answer №2

To find unique elements in an iterable, compare each element against the last one in a new array:

function findUniqueElements(iterable){
  var uniqueArray = []

  for(var index=0; index < iterable.length; index++){
    if(uniqueArray.length < 1){
      uniqueArray.push(iterable[index])
    } else if(iterable[index] !== uniqueArray[uniqueArray.length - 1]) {
      uniqueArray.push(iterable[index])
    }
  }

  return uniqueArray
}

Answer №3

Perhaps this solution will be beneficial:

let word = "hhhhheeeelllloooooohhheeeyyy";
function removeDuplicates(iterable) {
  let unique = [];
  unique[0] = iterable[0];
  for (let i = 1; i < iterable.length; i++) {
    if (iterable[i] !== unique[unique.length - 1]) {
      unique.push(iterable[i]);
    }
  }
  return unique;
}
alert(removeDuplicates(word));

The for loop is designed to adapt as unique elements are added or removed from the array.

This code has also been tested in Internet Explorer. Access the jsfiddle link here: https://jsfiddle.net/kannanore/z5gbee55/

Answer №4

let txt = "gggoooooddddmmooorrnnniiinng";
let txtLength = txt.length;
let newTxt = "";
for(let j=0; j < txtLength; j++ ){
    let letter$ = txt.charAt(j);  
    if(letter$ == txt.charAt(j+1)){
        txtLength = txt.length;`enter code here`
    }else{
        newTxt = newTxt + letter$ ;
    }
}
console.log(newTxt);
//Output: goodmorning

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my browser to display twice the height value?

After running the code below on my browser, I noticed that the height value is rendered double. To start off, I tested the following code in about:blank. In the HTML: ... <canvas id="canvasArea" style=" width: 500px; height: ...

"Phraseapp is in the process of refreshing the primary language document

I currently have a locale file that contains various text keys that need to be translated. Each key corresponds to a specific text that needs to be translated into different languages: { key1: "Text to translate", key2: "Another text to translate", ...

Getting dynamic variables in the `getStaticProps` function of NextJS can greatly enhance

I am working on utilizing getStaticProps in order to fetch data based on a variable. Here is a sample code snippet: export async function getStaticProps() { const res = await fetch(localWordpressUrl, { method: 'POST', headers: { 'C ...

Laravel 5.0 facing issues with AJAX requests

For my Laravel 5.0 project, I am utilizing Google API's for Google Oauth login. After successfully retrieving the email and id_token of the currently logged-in user, I aim to send this data to the SigninController to access our own API. The goal is to ...

Finding out whether the current date falls between a startDate and endDate within a nested object in mongoose can be done by using a specific method

My data structure includes a nested object as shown: votingPeriod: {startDate: ISOdate(), endDate: ISOdate()}. Despite using the query below, I am getting an empty object back from my MongoDB. const organizations = await this.organizationRepository.find( ...

Creating or updating JSON files using Node.js

I am currently working with JSON files that contain an array of objects. I am looking to update one of these objects and subsequently update the JSON file by overwriting the old file. I understand that this cannot be achieved using AngularJS, but rather wi ...

Initiate a click event on an anchor element with the reference of "a href"

I'm currently facing an issue with clicking a href element on my HTML website. The click event doesn't seem to be triggered. CODE: HTML CODE: <div class="button" id="info" ></div> <ul id="game-options"> <li><a ...

Encountering CROS Error persistently despite including a header in Node.js for AngularJS

Currently attempting to work with REST API in NODE JS for Angular JS. Despite adding the cors header in my server code, I continue to encounter the error message: XMLHttpRequest cannot load . Request header field Access-Control-Allow-Origin is not allowed ...

`Vue function is unable to find the definition of a variable`

I am struggling with utilizing a variable in a vue 3 application that has been emitted by a component called Mags. The variable is functioning properly in the importMags function, however, I am unable to access it within the handleSubmit function. It consi ...

Utilize Client Request Variable to NodeJS Server to Implement Middleware Routing

I am exploring the use of routes to serve pages from a nodejs server based on whether a user is logged in. My goal is to extract login session details from the client side and send them back to the NodeJS server, where they can be utilized in a middleware ...

Struggling to transfer information from Express backend to React frontend using Axios, facing obstacles

I'm attempting to transfer data from my Express backend to the React frontend using Axios, but I'm encountering difficulties. The data I'm trying to transmit is sourced from a text file. Backend: const express = require('express') ...

Is there a way to accurately retrieve the width of an element within setInterval without any delay?

I'm currently experimenting with increasing a progress bar using the setInterval function. So far, it seems to be functioning properly. var progressBar = $('.progress-bar'); var count = 0; var interval = setInterval(function () { va ...

When using a master page in ASP.Net webforms, the autocomplete feature may not function correctly

I'm encountering an issue with a script on my website. I have a web form called CoursesPage.aspx that utilizes a master page. I have implemented autocomplete functionality using jQuery on a textbox to display course names fetched from a database. The ...

Removing elements from a matrix in C was the topic at hand

Is there a way to remove even elements from the main and secondary diagonals of a square matrix, and only odd elements from the main diagonal? The issue lies in figuring out how to shift elements in a matrix while preserving the original order to achieve ...

Tips for transferring binary information from a Node.js socket.io (v2.0.x) server to a client in a web browser

When using Engine.io's send function to send binary data, it appears as binary in DevTools. However, Socket.io handles this data as JSON and sends it as text. Is there a way to access the Engine.io send function through a Socket.io instance? Perhaps ...

Error in Swift JSONDecoder - Anticipated Dictionary<String, Any> for decoding, but encountered an array instead

Recently delving into Swift 5.3, I'm encountering issues with fetching my nested JSON data. Here is a glimpse of how my JSON data result is structured: { "sites":[ { "site_no":"16103000", & ...

Show a status as "delivered" in SQL when a data field is empty

I'm developing a C# Windows Forms application for our end users that involves nullifying a value in one of our tables based on a customer account number. To achieve this, I am using a SqlDataAdapter with the following code snippet: string acct_no = " ...

Trouble with updating a variable within a loop in Cypress

During my experience with writing Cypress tests, I came across an issue that is preventing me from updating a specific variable. The goal of my test is to run a loop and update the questionId variable within each iteration for making API queries. However, ...

JavaScript function that takes an array of large objects and returns an array of smaller objects

Consider this scenario: I have a collection of large objects consisting of various attributes like ID, type, title, count, and more. { "id": "0165a74c-2545-40f7-9145-b95f5e5cb77e", "type": 4, "title": "My Title", "delete": false, "dele ...

Creating personalized functions in Object.prototype using TypeScript

My current situation involves the following code snippet: Object.prototype.custom = function() { return this } Everything runs smoothly in JavaScript, however when I transfer it to TypeScript, an error surfaces: Property 'custom' does not ex ...