Combining strings from an array while restricting repeated characters

I have an array of strings that need to be combined to form a single string, using a specific number referred to as the associatedNumber. This associatedNumber dictates that in the final result, all clusters of identical characters (from the array) should not exceed this associatedNumber in length.

Illustrative Example

exampleOutput = [
  'UUU', 'DD', 'UU',
  'UU', 'SSS','A',
  'B', 'C','U',
  'Y'
]

The desired output is:

UUUDDUUUSSSABCUY

Current Approach

The approach being taken currently is:

output = [
  'AAA', 'ZZZ', 'AA',
  'AA', 'X', 'K',
  'L', 'N', 'O',
  'P'
]
associatedNumber = 3;

for (i = 0; i < output.length; i++) {
    if (output[i] === associatedNumber);
    output.splice(i,1);
}
console.log(output)

Different Scenario

output = [
  'XXXX', 'GGG',
  'GG', 'XXX',
  'J', 'M',
  'H'
]

This should result in:

XXXGGGXXXJMH

Answer №1

To create a single string from an array, you can concatenate all the elements and then replace any groups of characters that exceed a certain length with a substring of that maximum length. Achieve this by using a regular expression for the replacement process:

function convertToString(arr, maxLength) {
   let regex = RegExp(`((.)\\2{${maxLength-1}})\\2+`, "g");
   return arr.join("").replace(regex, "$1");
}

let inputArray = [
  'MMM', 'GG', 'MM',
  'MM',  'XX', 'A',
  'B',   'D',  'M',
  'Z'
];
console.log(convertToString(inputArray, 3));

Answer №2

output.join().replace(/,/g, '')

output = [
  'MMM', 'GG', 'MM',
  'MM',  'XX', 'A',
  'B',   'D',  'M',
  'Z'
]
newString = output.join().replace(/,/g, '')

console.log(newString)

MDN Reference: .join .replace

Answer №3

There are several techniques you can use to combine, compare, transform and merge strings.

function y(array, limit) {
    return array
        .join('')
        .match(/(.)\1*/g)
        .map(str => str.slice(0, limit))
        .join('');
}

console.log(y(['MMM', 'GG', 'MM', 'MM', 'XX', 'A', 'B', 'D', 'M', 'Z'], 3));

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

I've exhausted all my knowledge but still unable to get Tailwind to work

I've been troubleshooting Tailwind for the past 6 hours. Managed to set it up in a simpler Nextjs/React/Typescript project, but struggling to get it working in this larger codebase. I'm sure I'm missing something obvious, but I'm at a ...

Understanding how flex-wrap property works in flexbox is essential for creating

Take a look at the code snippet below: .flex-container { padding: 20px; margin: 20px; list-style: none; border: 1px solid silver; -ms-box-orient: horizontal; display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -moz- ...

How to easily open a search page with just a click on the search field in CodeIgniter?

I am in the process of implementing a search feature in CodeIgniter. My view file is divided into two main sections: Header section, which includes the search bar <?php echo form_open('controller/live_search');?> <div class="toolba ...

AJAX/PHP causing delays due to lag problems

I've been trying to implement an asynchronous call in my PHP script, but I keep running into the same issue: "Maximum call stack size exceeded." This is causing severe lag on my site and I suspect there might be a loop somewhere in my code that I just ...

Challenges with incrementing in Jquery's each loop and setTimeout

http://jsfiddle.net/fxLcy/ - an example showcasing the use of setTimeout. http://jsfiddle.net/fxLcy/1/ - this demo does not include setTimeout. Although all elements are correctly positioned, I am in need of that delayed animation =/ My goal is to arrang ...

What is the process for implementing Sequelize to manage and modify multiple tables simultaneously?

I am currently working on developing the back-end with DB using Sequelize ORM. My main challenge is creating or updating data in multiple tables simultaneously. Below are some examples of what I am trying to achieve: //Tables const main = sequelize.define ...

Utilizing HTML and Javascript for streaming audio and recording voice

Working on a new project that involves streaming audio files (mp3) and recording voice messages. Initially considered using Flash, but the challenge is making the website iPhone-friendly as per the client's request. Is there a technology available th ...

Effective approach to exchange information among controllers in AngularJS

There are numerous techniques available to share data between controllers in Angular, such as accessing prototypical data from a parent scope, utilizing scope events for controller communication, or implementing shared services. However, what is considere ...

Which is the preferred method: utilizing ajax calls from assets/javascript/*.js or *.js.erb views?

I am developing an admin service on Rails that communicates with a network communicator. Here is my challenge: When a user clicks a button, they are presented with network groups to choose from. Once the user selects a group, they should be able to see th ...

Discovering ways to optimize argument type declarations in TypeScript

If we consider having code structured like this: function updateById( collection: Record<string, any>[], id: number, patch: Record<string, any> ): any[] { return collection.map(item => { if (item.id === id) { return { ...

Prevent draggable functionality of jQuery UI on elements with a specific class

I have created a dynamic cart feature where users can drag and drop items into the cart. However, once an item is placed in the cart, it should no longer be draggable (though still visible but faded). I attempted to achieve this by using the following code ...

Most effective method for streamlining conditional checks in JavaScript

To enhance the quality of my code and improve its readability, I have decided to implement a currying functions approach and create pure helper functions for repetitive code snippets. One issue I noticed was the frequent existence/type checks throughout my ...

Replace the image with text inside an anchor when the anchor is being hovered

I want a logo (we'll call it .item-logo) to be shown inside a circle when not being hovered over, but when you hover over the container, the date should be displayed. Here is the HTML code: <div id="main-content" class="container animated"> ...

Steps for refreshing a JavaScript function responsible for generating a table

Within the code snippet provided, there is a click event attached to a table row. Upon clicking a row, the script extracts the id value from the first column and triggers a REST call. Subsequently, a new table is constructed using a third-party function ca ...

Tips for personalizing the export grid menu in angular-ui-grid?

My grid includes an external "Show Details" option that adds extra columns to the grid when clicked. https://i.sstatic.net/Fu2Qp.png The problem arises with the options for "Export all data" and "Export visible data," which can be confusing in this scena ...

Utilizing webpack 4's JSON tree-shaking functionality for keys that include the hyphen character

I need assistance with utilizing webpack 4's JSON tree-shaking feature as I am encountering a hurdle. Here is an example of some functional code: import { accessibility_16 } from '@collab-ui/icons/data/iconsData.json'; console.log("access ...

What is the best way to transfer the array from my function and have it returned?

I've been struggling to successfully pass my array to an external function. Can anyone help me with this? You can find the code that I'm working on in jsbin: https://jsbin.com/kugesozawi/edit?js,console,output. The expected result should be passe ...

The constant reloading of the page is hindering the crucial display of the data

After successfully getting something to work, I noticed that the data disappears when the page refreshes. How can I prevent this from happening? <html> <head> <meta charset="utf-8"> <title> IT Services </ti ...

Connecting a specific URL of an API to a single mobile app: A step-by-step guide

Currently, my API includes a user registration system that is utilized by a mobile application. Most of the URLs are restricted for anonymous users and require a token key for authorization, except for the register URL. The register URL needs to remain op ...

Skipping the configuration file during the process of converting Node.js files to an executable using pkg

I am currently working on a node.js application and in order to prevent users from reading the code, I am attempting to convert my JavaScript files to executable files. I have been using the pkg module for this task, but I have encountered an issue. The p ...