Splitting an array based on the number of characters it contains in a dynamic manner

I am working with an array that looks like this:

const testArray = [ 'blah', 'abc​testtt​​', 'atestc​', 'testttttt' ]

My goal is to split the string once it reaches a certain character count, say 10 characters. In addition, I want the output to adjust itself to fit within 10 characters. If this concept is unclear, please refer to the expected output below for clarification. Let's assume each item in the array will not exceed 10 characters for illustration purposes.

When the testArray exceeds 10 characters, I would like the next element to be stored under a new variable perhaps? I am open to alternative methods if this approach is inefficient.

const testArray = [ 'blah', 'abctesttt​​', 'atestc', 'testttttt' ]
if ((testArray.join('\n')).length) >= 10 {
    /* Would it make sense to split the string into parts and store it in a new variable maybe?
    console.log((the_splitted_testArray).join('\n')); */

}

Expected result:

"blah
atestc" // Instead of using "abctesttt", it should use "atestc" from the array to avoid exceeding the 10-character limit. If adding "atestc" would surpass the limit, it should check the next element.

"abctesttt" // It cannot include the remaining "testttttt" as it would exceed the character limit set

"testttttt"

Answer №1

In order to efficiently manage your strings at run time, one approach is to utilize a "parent" array that can store a maximum of 10 strings. Creating new variables dynamically during runtime may not be feasible, so working within the constraints of a predefined structure like this could be beneficial.

When it comes to grouping these strings, you'll need to devise an algorithm that suits your specific needs. One possible approach involves iterating through the initial array and organizing the strings into a two-dimensional array based on their lengths. From there, you can begin grouping them together in a way that optimizes space usage.

  1. Sort the strings from the original array into a new structure, keeping track of messages with similar lengths - e.g.,
    $stringLength[$messagesWithSameLength[]]
    .
  2. Efficiently group the strings by starting with the longest ones and filling up available space with suitable matches. If no fit is found, start a new group to maximize space utilization.

Ultimately, the goal is to use the available space wisely while optimizing the grouping of strings for efficiency.

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

Clicking the load more button fails to retrieve any additional content

Recently, I implemented a "load more" button on my website's front page. The idea is for this button to load additional posts after every 15 posts. Despite having all the necessary code in place, clicking the button does not trigger any posts to load. ...

PhantomJS Alert: UnresolvedPromiseRejectionNotice

My main objective is to extract data from a website using Node.js. I have successfully managed to gather information using the request package, however, the website I am targeting contains dynamic content which cannot be accessed solely with request. Aft ...

Choosing the subsequent element that comes before

<tr class="main"></tr> <tr class="emails-details"> <button>some button</button> </tr> <tr class="main"></tr> <tr class="emails-details"> <button>some button</button> </tr> &l ...

Eliminating items from an array that is multidimensional

Hey there, I'm currently facing some issues with unsetting an entire row from a multidimensional array. The format of my array is as follows: Array ( [0] => Array ( [ID] => 10000 [Date] => 21/11/2013 ...

SyntaxError was not caught and an unexpected token export occurred at line 2371 in the popper.js file

I'm a beginner with bootstrap and jquery, and I'm attempting to utilize the datatables feature for sorting. However, when I run my code, I encounter the following error in the console: uncaught SyntaxError: Unexpected token export at popper.js:2 ...

Is it possible to specify the timing for executing Typescript decorators?

One issue I've encountered is that when I define a parameterized decorator for a method, the decorator runs before the method itself. Ideally, I'd like the decorator to run after the method has been called. function fooDecorator(value: boolean) ...

How can the outer function be connected to the resolve method of $routeProvider?

Here is a functional code snippet: $routeProvider.when('/clients', { templateUrl:'/views/clients.html', controller:'clientsController', resolve: { rights: function ( ...

Using a loop in a Vue.js slick slider: easy step-by-step guide

While utilizing vue-slick link https://www.npmjs.com/package/vue-slick within a bootstrap modal, I encountered an issue when using a v-for loop to iterate through the items. The problem can be seen in this example: https://i.sstatic.net/PhJCE.jpg. Below i ...

Utilize the arrow keys to navigate through the search suggestions

I am facing an issue with my search bar where I am unable to navigate through the suggestions using arrow keys. I have been struggling with this problem for days and would appreciate any help in resolving it. var searchIndex = ["404 Error", "Address Bar ...

AngularJS: The `$locationChangeStart` event

I am attempting to check the next token in the next, but I am encountering an error: TypeError: next.localStorage is not a function APP.JS .run(function ($rootScope, $location,$log,User) { $rootScope.$on("$locationChangeStart", function (event,nex ...

Vue Router configuration functions properly when accessed through URL directly

I need guidance on how to handle the routing setup in this specific scenario: Below is the HTML structure that iterates through categories and items within those categories. The <router-view> is nested inside each category element, so when an item i ...

Eliminate any leading or trailing spaces around a string contained within a tag within a contenteditable div

I am working on a project to eliminate extra spaces before and after text within a bold tag. Functionalities: I developed a text editor where users can type text, select it, and apply bold formatting. Additionally, there is an HTML button that displays th ...

Modify path and refresh display upon ajax call to node server

Recently, I made the decision to utilize a Node server as a proxy for making API calls to third-party public APIs from my front end. After successfully sending a request to my Node endpoint and then to the third-party API, I received the expected response. ...

Encountering a 404 Error while using GetStaticPaths in NextJs

Having issues with Next JS dynamic routes resulting in a 404 Error. Initially attempted debugging by setting it up dynamically, then manually at http://localhost:3001/question/62e7b69ca560b1c81aa1a853 but still encountering the same issue. Tried toggling f ...

The elements in my code are not displaying as expected

This is my jQuery script: $("#options").popup(null, Settings.DialogOptions) .on("onOk", function(){ Settings.SaveSettings( ); Settings.CloseSettings( ); switch(Settings.GetSetting("displayId")){ case "true": $("#nextId").s ...

Tips on adding an image using Reactjs

I am currently working in Reactjs with the Next.js framework. I am attempting to upload images using Axios (POST method API) and will be utilizing an "api in PHP". Could someone please guide me on how to achieve this? I have tried the code below, but it&ap ...

Interacting with PHP through JavaScript function calls

I am facing some frustration with my website due to an issue involving PHP. When I retrieve data from a PHP file, it returns a JSON list like this: {"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurst ...

Utilizing HTML templates efficiently without the need for a view engine

For a new application, we are implementing multiple servers for handling different functions - one server for delivering HTML files, another as a proxy to handle HTTPS requests, and a Java backend with a database. The view server should be simple, with an ...

After making a request with HttpClient, the response can either be an empty body or a body

Encountering issues with HttpClient while trying to post data, I am faced with two distinct errors: When booking is treated as an object, the error message reads: Backend returned code 400, body was: [object Object]. Converting booking to JSON format by ...

The incorporation of zoom disrupts the smooth scrolling capability of the menu

My landing page has a menu that scrolls users to the selected section. However, my client prefers the page at a 90% zoom level. To accommodate this request, I added the following line of code: body { zoom:90%; } Unfortunately, when I click on a menu o ...