Dividing and joining a JavaScript array into segments based on character length

Suppose I have an array structured like this:

let inputArr = [
"Name: Jarina Begum↵Age: 70 years↵↵",
"Tab. Mycofree (250 mg)↵১ + 0 + ১/২ টা -- ১.৫ মাস -- খাওয়ার পরে↵",
"Cap. Losectil (20 mg)↵১ + 0 + ১ টা -- .১.৫ মাস -- খাওয়ার আগে↵",
"Tab. Rupin (10 mg)↵0 + 0 + ১ টা -- .১.৫ মাস -- খাওয়ার পরে↵",
"Savoy Sulphur Soap↵.১.৫ মাস -- নিয়মিত ব্যবহার করবেন।↵",
"Advices:",
"১।নিয়মিত ওষুধ সেবন করবেন।, ",
"২।সাধারন সাবান লাগাবেন না।, ",
"৩।পরিধেয় জামা কাপড় Savlon/Detol দিয়ে ধুয়ে ফেলবেন, ",
"৪।পরিবারের সবার চিকিৎসা করতে হবে।, ",
"৫।কবিরাজী ও হোমিওপাথি করবেন না, ",
"৬।ডাক্তার এর পরামর্শ বাতিত ওষুধ বন্ধ করবেন না।"
];

The task is to create a new array by joining elements from the given array where each element's character count should be <=300.

To achieve this, concatenate the elements one after another, keeping track of the character size & index of the array. Once the concatenation exceeds the limit [which is 300 in this case], push it into a new array, and start counting characters from the next index considering the character size from 0.

This process continues until the last index of inputArr.

If any element's size is >300, break that element into chunks of 300 characters each.

The expected output will look something like this:

[
"Name: Jarina Begum↵Age: 70 years↵↵Tab. Mycofree (250 mg)↵১ + 0 + ১/২ টা -- ১.৫ মাস -- খাওয়ার পরে↵Cap. Losectil (20 mg)↵১ + 0 + ১ টা -- .১.১৫ মাস -- খাওয়ার আগে↵Tab. Rupin (10 mg)↵0 + 0 + ১ টা -- .১.1৫ মাস -- খাওয়ার পরে↵Savoy Sulphur Soap↵.১.১5 মাস -- নিয়মিত ব্যবহার করবেন।↵Advices:",
"১।নিয়মিত ওষুধ সেবন করবেন।, ২।সাধারন সাবান লাগাবেন না।, ৩।পরিধেয় জামা কাপড় Savlon/Detol দিয়ে ধুয়ে ফেলবেন, ৪।পরিবারের সবার চিকিৎসা করতে হবে।, ৫।কবিরাজী ও হোমিওপাথি করবেন না, ৬।ডাক্তার এর পরামর্শ বাতিত ওষুধ বন্ধ করবেন না।"
];

In summary, here are the requirements:

  1. Create a new array by concatenating elements from a given array where the total character count of elements does not exceed <=300
  2. If the character count of any element in the original array is >300, divide it into chunks with a limit of 300 characters and splice them back into the original array.

Answer №1

To efficiently achieve this, you can utilize the .match method along with RegEx like so:

let characterLimitArray = inputArr.join().match(/.{1,300}/g)
console.log(characterLimitArray);

let inputArr = [
"Name: Jarina Begum↵Age: 70 years   ↵↵",
"Tab. Mycofree (250 mg)↵১ + 0 + ১/২ টা -- ১.৫ মাস -- খাওয়ার পরে↵",
"Cap. Losectil (20 mg)↵১ + 0 + ১ টা -- .১.৮ মাস -- খাওয়ার আগে↵",
"Tab. Rupin (10 mg)↵0 + 0 + ১ টা -- .১.৫ মাস -- খাওয়ার পরে↵",
"Savoy Sulphur Soap↵.১.৮ মাস -- নিয়েমিত ব্যবহার করবেন।↵",
"Advices:",
"১।নিয়মিত ওষুধ সেবন করবেন।, ",
"২।সাধারন সাবান লাগাবেন না।, ",
"৩।পরিধেয় জামা কাপড় Savlon/Detol দিয়ে ধুয়ে ফেলবেন, ",
"৪। পরিবারের সবার চিকিৎসা করতে হবে।, ",
"৫।কবিরাজী ও হমিওপাথি করবেন না, ",
"৬।ডাক্তার এর পরামর্শ বাতিত অষুধ বন্দ করবেন না।"
];
console.log(inputArr.join().match(/.{1,300}/g))

We hope this solution is useful to you...

Answer №2

Thanks to all who took the time to help me with my issue, even though it didn't meet all of my requirements. Nevertheless, I managed to solve it using a traditional loop.

I created three functions to address this problem - one for the first requirement and two for the second.

Function One: This function takes two parameters: an array and the character limit length.

Within this function, I call the second function, passing in the given array and storing the result as an input array.

const chunkSmsArr = (arr, len=300) => {
    let inputArr = checkElLength(arr, len);
    let outputArr = [];
    let msgString = '';
    let count = 0;

    for(let i=0; i<inputArr.length; i++) {
        if ((msgString + inputArr[i]).length <= len) {
            msgString += inputArr[i];
        } else {
            msgString = '';
            msgString += inputArr[i];
            count++;
        }
        outputArr[count] = msgString;
    }

    return outputArr;
}

Function Two: This function checks each element in the provided array. If the length of any element is greater than 300, it calls the third function to break the string into array elements and splices it at the current iteration position.

const checkElLength = (inputArr, len) => {
    let outputArr = [];
    for(let i=0; i<inputArr.length; i++) {
        if (inputArr[i].length > len) {
            let breakedSmsArr = breakSmsArrString(inputArr[i], len);
            inputArr.splice(i, 1, ...breakedSmsA`rr);
        }
    }
    outputArr = inputArr;
    return outputArr;
}

Function Three: In this function, I also pass two parameters: the string that needs to be broken into array elements and the character limit length.

const breakSmsArrString = (str, len) => {
    let curr = len;
    let prev = 0;
    let output = [];

    while(str[curr]) {
        if(str[curr++] == ' ') {
            output.push(str.substring(prev,curr));
            prev = curr;
            curr += len;
        } else {
            let currReverse = curr;
            do {
                if(str.substring(currReverse - 1, currReverse) == ' ') {
                    output.push(str.substring(prev,currReverse));
                    prev = currReverse;
                    curr = currReverse + len;
                    break;
                }
                currReverse--;
            } while(currReverse > prev)
        }
    }
    output.push(str.substr(prev)); 
    return output;
}

You can now test the output using console.log:

console.log(chunkArr(inputArr, 300));

Answer №3

Here is an alternative approach using a basic for loop.

  let inputArr = [
  "Name: Jarina Begum↵Age: 70 years   ↵↵",
  "Tab. Mycofree (250 mg)↵১ + 0 + ১/২ টা -- ১.৫ মাস -- খাওয়ার পরে↵",
  "Cap. Losectil (20 mg)↵১ + 0 + ১ টা -- .১.৫ মাস -- খাওয়ার আগে↵",
  "Tab. Rupin (10 mg)↵0 + 0 + ১ টা -- .১.৫ মাস -- খাওয়ার পরে↵",
  "Savoy Sulphur Soap↵.১.৫ মাস -- নিয়েমিত ব্যবহার করবেন।↵",
  "Advices:",
  "১।নিয়মিত ওষুধ সেবন করবেন।, ",
  "২।সাধারন সাবান লাগাবেন না।, ",
  "৩।পরিধেয় জামা কাপড় Savlon/Detol দিয়ে ধুয়ে ফেলবেন, ",
  "৪। পরিবারের সবার চিকিৎসা করতে হবে।, ",
  "৫।কবিরাজী ও হমিওপাথি করবেন না, ",
  "৬।ডাক্তার এর পরামর্শ বাতিত অষুধ বন্দ করবেন না।"
  ];

let expectedArr = [];
let driverString = '';
var count = 0;
var length_= 0;
for(var i = 0; i < inputArr.length; i++){
   length_  = inputArr[i]+ driverString;
   if(length_.length <= 300 ){
    driverString = driverString + inputArr[i]; 
   }else{
    driverString = '';
    driverString = driverString + inputArr[i]; 
    count++;
    length_= 0;
   }
  expectedArr[count] = driverString;
}
console.log(expectedArr,expectedArr.length)

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 is the best way to determine if a radio button has been chosen, and proceed to the next radio button to display varied information?

The goal is to display the <div class="resp"> below each radio button when it is selected, with different content in each <div class="resp">. The previously selected <div class="resp"> should be hidden when a new radio button is chosen. O ...

What steps can be taken to turn off specific warning rules for CSS mode in ACE editor?

Utilizing the Ace Editor (through Brace and React-Ace) is a key aspect of my project. In our implementation, we specify the editor's mode as "css" and integrate it into our webpage. While this setup functions correctly, we have observed that some of ...

What methods are available for integrating ArcGIS JS into Vue.js?

I have been exploring the examples provided in the documentation for ArcGIS, but I am facing difficulties in using it correctly. For instance, when I try to import Map from ArcGIS as demonstrated in this example: import Map from '@arcgis/Map' I ...

Employing ExpressJS on the server side and JQuery on the client side for handling static links

Recently delved into the world of jQuery and node.js, and everything was smooth sailing until I hit a roadblock. Despite my best efforts to search online, I couldn't find a solution to my problem. It seems like a simple issue, but I just can't fi ...

After successfully sending a GET request to the API, the Next.js 13.4.3 website still does not reflect new posts added on the hosting platform

I am currently using Next.js version 13.4.3 in my app directory to create a blog site. However, I am facing an issue. When I run npm run build locally on my computer and then start with npm run start, the new posts are displayed normally after adding them ...

Encountering issues while attempting to execute node-sass using npm

Currently, I'm attempting to execute node-sass using npm. Displayed below is my package.json: { "name": "my-project", "version": "1.0.0", "description": "Website", "main": "index.js", "scripts": { "sass": "node-sass -w scss/ -o dist ...

JavaScript code to retrieve an image from an <img> tag's source URL that only allows a single request and is tainted due to cross-origin restrictions

I have an image displayed in the HTML DOM. https://i.stack.imgur.com/oRgvF.png This particular image (the one with a green border) is contained within an img tag and has a URL as its source. I attempted to fetch this image using the fetch method, but enc ...

Unable to import the configuration module that is located three directories away in a Node.js environment

Within user.controller.js, there is a line that reads as follows: const config = require(".../config");. To provide some context, here is a visual representation of my directory structure: https://i.stack.imgur.com/dCkp1.png ...

Transforming JSON/XML into a hierarchical display

I've come across the following XML file: <Person attribute1="value1" attribute2="value2"> value3 <Address street="value4" city="value5">value6</Address> <Phone number="value7" type="value8">value9</Phone> </Pers ...

Is there a way to stop Bootstrap from automatically bolding the font?

When testing this simple example without the bootstrap link, everything seems to be working correctly: Hovering over any word changes its color to red, and when hovering away it returns to black. But as soon as the bootstrap link is included, the text bec ...

What method can I use in C++ to quickly duplicate an array on the go?

I've been mulling over this question for a while now. I'm currently weighing the options between: memcpy std::copy cblas_dcopy Is there anyone who can shed some light on the advantages and disadvantages of using these three options? Any other ...

Utilize array in Laravel view with VueJS

When using Laravel, I have a ProdoctController and CategoryController. In the ProdoctController, I am passing category data with the following function: public function view(){ $category = Category::all(); return view('admin.product.main',[& ...

I am encountering an issue with CreateJS where I receive the error message: "createjs is not defined"

Looking for assistance with my createJS issue. var stage = new createjs.Stage(canvas); Encountering the following error : angular.js:13642 ReferenceError: createjs is not defined, even though I have EaselJS in my bower-components. Appreciate any hel ...

Template for event cell details in Angular2 calendar view

Currently utilizing [angular-calendar] from github.com/mattlewis92/angular-calendar . My goal is to incorporate my own template as a detailed view for events. I am aiming to achieve a similar effect as shown in the image: final effect So far, I ha ...

I must utilize the MongoDB native driver to retrieve unique IDs sorted by a timestamp column

I am currently utilizing the nodejs mongodb native driver for developing a chat application. Within my database, I have a collection named dialog which contains fields for sessionId and dateCreated (timestamp). My objective is to retrieve a list of distinc ...

What is the best way to retrieve the value from a custom attribute in a React element?

Here is the HTML I am currently working with: <select onclick={this.handleClick}> <option key="1" value="aaa" data-plan-id="test"></option> </select> Below is the code for my handleClick event: console.log(e.target.value); ...

Ways to delete a CSS attribute with jquery

Is there a way to eliminate a CSS property from a class without setting it to null? Let's say I have a class called myclass with the property right:0px. I want to completely remove right:0px from my class, not just set it to null. How can I achieve th ...

Is it possible to encounter an invalid character when trying to parse valid JSON using

I have an object with properties that contain JSON strings. When I serialize this object, I get the following string: [{ "template": 1, "action_json": "{\"id\":\"1\",\"action\":\"An action for all of IT!\",& ...

directive in Angular ordering

After exploring this link, my understanding deepened: http://plnkr.co/edit/k5fHMU?p=preview Upon analyzing the code snippet provided in the link above, I noticed that the Angular app consists of both a controller and a directive. However, there seems to ...