Utilizing loops to generate multiple arrays from a given string

I have a sequence of values:

"000111111122222223333333444455556666"

Is it possible to utilize three separate loops to generate multiple arrays based on different index ranges? For instance, producing an array from index 0 to 3 ([000]), then creating arrays using the index ranges 3 to 10, 10 to 17, and 17 to 24 ([1111111], [2222222], [333333]), followed by another loop for index values ranging from 24 to 28, 28 to 32, and 32 to 36 ([4444], [5555], and [6666])?

In summary, a total of three distinct arrays would be generated utilizing three unique for loops.

array1 = [000]
array2 = [1111111, 2222222, 333333]
array3 = [4444, 5555, 6666]

Answer №1

If you're looking to experiment with a code snippet, here's a simple solution for reference:

var inputString = "000111111122222223333333444455556666" ;

var array1 = [] ;
var array2 = [] ;
var array3 = [] ;


var currentChar ;

for (var index = 0 ; index < inputString.length ; index++) {

    currentChar = inputString.substring(index,index) ;

    if (index < 3) {
        array1.push(currentChar) ;
        continue ;
    }

    if (index >= 3 && index < 10) {
        array2.push(currentChar) ;
        continue ;
    }
    :
    :

}

Answer №2

This solution seems like it could be effective.

let str = '000111111122222223333333444455556666';

function createArray(str, element) {
    let start = str.indexOf(element);
    let end = str.lastIndexOf(element) + 1;
    return [str.substring(start, end)];
}

const firstSet = createArray(str, 0);
const secondSet = [].concat(createArray(str, 1))
                     .concat(createArray(str, 2))
                     .concat(createArray(str, 3));
const thirdSet = [].concat(createArray(str, 4))
                    .concat(createArray(str, 3))
                    .concat(createArray(str, 3));

Answer №3

To solve this problem, one approach is to divide the string into smaller substrings.

var str = '000111111122222223333333444455556666',
    parts = [[3], [7, 7, 7], [4, 4, 4]],
    result = parts.map((i => a => a.map(l => str.slice(i, i += l)))(0));

console.log(result);

Answer №4

const breakDown = (text, start, end) => {
    let resultArr = [],
        subStr = text[start],
        separator;

    for (let j = start + 1; j < end; j++) {
        let character = text[j];
        if (character === subStr[0])
            subStr += character;
        else {
            resultArr.push(subStr);
            subStr = character;
        }
    }
    resultArr.push(subStr);
    return resultArr;
}

breakDown("00011122", 0, 8)

["000", "111", "22"]

Answer №5

If you want to achieve this dynamically, you can utilize the .split() and .map() methods to convert a string into an array, then group the items of this array based on their values.

Here is an example of how the code should look:

const str = "000111111122222223333333444455556666";

var groupArrayByValues = function(arr) {
  return arr.reduce(function(a, x) {
    (a[x] = a[x] || []).push(x);
    return a;
  }, []);
};

var arr = str.split("").map(v => +v);
var result = groupArrayByValues(arr);

This will provide you with an array containing separate arrays grouped by similar values.

Check out the demo below:

const str = "000111111122222223333333444455556666";

var groupArrayByValues = function(arr) {
  return arr.reduce(function(a, x) {
    (a[x] = a[x] || []).push(x);
    return a;
  }, []);
};

var arr = str.split("").map(v => +v);
var result = groupArrayByValues(arr);


console.log(result);

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

Retrieve the screen width using a JavaScript function and apply it as a percentage

I find myself needing to adjust the size of table elements based on the width of the screen. While I am not well-versed in javascript or html, resolving this issue is crucial. Unfortunately, I did not create the original asp page and have limited ability t ...

Pressing the button in JqGrid will assign an identification number

I am facing an issue with selecting rows in my JqGrid, so I found a solution on which suggests that I need an ID for every row. Whenever I add data to my Grid by pressing a button, I tried assigning each row an ID using a simple click counter function. H ...

Having trouble loading events on Fullcalendar.io?

Our team is utilizing fullcalendar.io and aiming to retrieve an event from our API controller. The Controller [Route("api/Bookings")] public class BookingApiController { // GET [HttpGet] public string Get() { ...

Custom JavaScript function throwing an error

function changeElementClass(path, changeClass, duration){ $(path).removeClass(changeClass); $(this).addClass(changeClass); )}; $('.flightDetails .option').changeElementClass('.flightDetails .option','selected',300); ...

Storing a collection of strings in a mongoose schema: A step-by-step guide

I am working with a user schema that looks like this: const UserSchema = mongoose.Schema({ username: { type: String, required: false }, social: [{ facebook: { type: String, required: false ...

Can you explain the mechanics behind Angular Component CSS encapsulation?

Is it possible to avoid CSS conflicts when using multiple style sheets? Consider Style 1: .heading { color: green; } And Style 2: .heading { color: blue; } If these two styles are applied in different views and rendered on a layout as a Partial Vi ...

Tips on incorporating the source path from a JSON file into a Vue component

Is there a way to render images if the path is retrieved from a JSON file? Typically, I use require('../assets/img/item-image.png'). However, I'm uncertain how to handle it in this scenario. Component: <div v-for="(item, index) in i ...

Is there a way to improve scrolling speed on Mobile Safari?

I'm currently working on a project utilizing angularjs and bootstrap, aiming to replicate iOS's navigationController feature. However, I'm encountering speed issues, particularly when scrolling between views on mobile safari iOS. The transi ...

Incorporate an image into the React state in order to showcase it within a personalized

Objective I am aiming to create a dropdown menu that allows users to select images instead of text. Context I have integrated a react dropdown component into my file, and it works well with text options. However, I am facing difficulties in displaying i ...

Rendering an element in React Router Dom based on specific conditions

Starting a new project with the latest version of react-router-dom and following their recommendation to use createBrowserRouter. The goal is to display a different header based on the path parameters. Currently, I have set up an optional path parameter: ...

In Next.js, a peculiar issue arises when getServerSideProps receives a query stringified object that appears as "[Object object]"

Summary: query: { token: '[object Object]' }, params: { token: '[object Object]' } The folder structure of my pages is as follows: +---catalog | | index.tsx | | products.tsx | | | \---[slug] | index.tsx | ...

Error occurred while looking for user by ID in the everyauth

I previously had a working example with express 2.*, but now I am transitioning to version 3.*. The issue arises during authentication with Facebook, causing some problems. Everything works fine until everyauth makes the GET request to Facebook and then re ...

Utilizing the ng-if directive to choose the second element within an iteration of an ng-repeat loop

I am currently working on a project where I need to organize and group content by day. While the grouping function is working fine, I am facing an issue with treating the first two items in the loop differently from the rest. I have experimented with using ...

What is the method for locating an element within an array?

The content being returned is presenting a challenge. How can I retrieve data from inside 0? I attempted to access it using date[0] without success const { data } = getData(); The result of console.log(data) is shown below: enter image description here ...

Calculate the total values of nested objects within an array of objects

I encountered an array of objects with various properties - [{ title: "oranges", id: 5802537, cart: { purchased: 3, stockTotal: 9 }, price: 3, department: "fresh fruit and veg" }, { title: &qu ...

Trouble with sending input through Ajax in HTML form

I'm facing a dilemma that I can't solve. The issue arises from a page (index.php) that begins by opening a form, then includes another PHP page (indexsearch.php), and finally closes the form. The included page works with a script that displays d ...

Switch up Three.js texture in externally imported Collada model

Currently, I am using the three.js collada loader to bring in an .dae file that includes a texture (.png) image. The challenge I am facing involves replacing this original .png file with a new texture generated from a canvas element and saved in .png forma ...

Tips for refreshing the Vuex store to accommodate a new message within a messageSet

I've been working on integrating vue-socket.io into a chat application. I managed to set up the socket for creating rooms, but now I'm facing the challenge of displaying messages between chats and updating the Vuex store to show messages as I swi ...

Playing with Data in AG-Grid using Javascript

I am working on implementing data display using AG Grid with an AJAX call, but I am facing an issue where no data is being shown in the grid. Even though my AJAX call seems to be functioning correctly and returning the desired object List, the grid itsel ...

Use PHP to process a form submission and use AJAX to send a response back to the user

Currently in the process of developing a website and I am seeking guidance on how to utilize ajax to submit form data instead of relying on the html action attribute. A PHP script has been written that may produce different outcomes, and I want ajax to not ...