Creating a multidimensional array or array tree from a list of arrays - A step-by-step guide!

My challenge involves working with an array that looks like this:

["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"]

The goal is to create subarrays with a combined character length of 10, resulting in something like this:

[
  ["Lorem", "Ipsum"],
  ["Colo", "sit", "ame"], 
  ["consecteur"]
]

I attempted the following approach:

var arr = ["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"];
var combArr = [];
var charCount = 0;

for (i = 0; i < arr.length; i++) {
    charCount += arr[i].length;
    if (charCount <= 10) {
        combArr.push(arr[i]);
    }
    if (charCount > 10 && charCount <= 20) {
        combArr.push(arr[i]);
    }
    // ...
}   

However, my current method only retains the elements that meet the condition, ultimately maintaining the original order of the items. I am seeking guidance on how to achieve the desired multidimensional array structure as shown above. Any assistance you can provide would be greatly appreciated. Thank you!

Answer №1

Below is an updated version of the code you provided:

let words = ["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"];
let combinationArray = [];
let characterCount = 0;
let currentWords = []; // MODIFIED: storing current list of words

for (j = 0; j < words.length; j++) {
    if (characterCount && (characterCount + words[j].length > 10)) {
        // save current list
        combinationArray.push(currentWords);
        // ... then initialize new list
        currentWords = [];
        characterCount = 0;
     }
     characterCount += words[j].length;
     currentWords.push(words[j]);
}   
// add remaining list to result:
combinationArray.push(currentWords);

Answer №2

The key element you are overlooking is the necessity to generate fresh arrays and then insert those multiple arrays into a main array.

Here's an illustration to help you understand;

var basket = [];
var carton1 = [];
var carton2 = [];

carton1.push("apple");
carton1.push("orange");

carton2.push("banana");

basket.push(carton1);
basket.push(carton2);

console.log(basket); // [["apple", "orange"], ["banana"]]

I'll leave it up to you to figure out how to apply this concept to your specific problem, but I hope this explanation helps you move forward. Best of luck!

Answer №3

If you're looking for a solution, you could consider implementing the following approach.

let words = ["Apple", "Banana", "Cherry", "Date", "Elderberry"];
const MAX_LENGTH = 8;
let groupedWords = words.reduce(function(prev, curr) {
  if (prev.length === 0) {
    prev.push([curr]);
  } else {
    let currentGroupLength = prev[prev.length-1].reduce(function(iprev, icurr) {
      return iprev + icurr.length;
    }, 0);
    if (currentGroupLength + curr.length > MAX_LENGTH) {
      prev.push([curr]);
    } else {
      prev[prev.length-1].push(curr);
    }
  }
return prev;
}, []);
console.log(groupedWords)

Answer №4

To improve your code, you can enhance it by introducing an additional level of nesting in the combArr array, resetting the charCount variable for each new 'row,' and addressing the scenario where the first element of the arr array exceeds 10 characters by including || i == 0 in the if-condition:

var arr = ["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"];
var combArr = [[]];
var charCount = 0;

for (i = 0; i < arr.length; i++) {
    charCount += arr[i].length;
    if (charCount <= 10 || i == 0) {
        combArr[combArr.length-1].push(arr[i]);
    } else {
        charCount = arr[i].length;
        combArr.push([arr[i]]);
    }
}

console.log(combArr);

A more efficient approach is shown below:

function format(array, chars) {
  var result = [], chars = 0, prev = 0, length = array.length;
  for (var i = 0; i < length; ++i) {
    chars += array[i].length;
    if (i && chars > 10) {
      result.push(array.slice(prev, i));
      chars = array[i].length;
      prev = i;
    }
  }
  result.push(array.slice(prev, length));
  return result;
}

console.log(format(["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"]));
console.log(format(["12345678901", "", "1234567890", "", "1"]));

Answer №5

Give this a shot; (modified)

 var arr = ["1234567890","hidden","para","meter"];
    var results= [];
    var charCount = 0;
    var temp=[];
    for (var i = 0; i < arr.length; i++) {
      charCount += arr[i].length;
        if(charCount>10){
          results.push(temp);
          charCount=arr[i].length;
          temp=[arr[i]];
        }else{
          temp.push(arr[i]);
        }
    }
    if(temp.length){results.push(temp);}
    document.write(JSON.stringify(results))

Give this a try;

var arr = ["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"];
var results= [];
var charCount = 0;

for (var i = 0,temp=[]; i < arr.length; i++) {
    if((charCount += arr[i].length)>=10){
      temp.push(arr[i]);
      results.push(temp);
      charCount=0;
      temp=[];
    }else{
      temp.push(arr[i]);
    }
}
document.write(JSON.stringify(results))

Answer №6

This solution addresses the following shortcomings:

  1. The solution does not account for the input array being in an incorrect order, preventing a complete pairing of 10 characters. For instance, it would not function properly with an input array like ["hello", "whatever"].
  2. It also fails to consider the conditional splitting of an array item into two separate arrays. For example, with the input array ["hello", "whatever"], the output should be [["hello", "whate"],["ver"]].

Based on the provided information, you can experiment with this code snippet:

var inputArray = ["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"];
    var tempArray = [];
    var finalArray = [];
    var charCount = 0;

    for (i = 0; i < inputArray.length; i++) {

        if ((charCount + inputArray[i].length) <= 10) {

            charCount += inputArray[i].length;

            tempArray.push(inputArray[i]);

            if (charCount == 10) {
                finalArray.push(tempArray);
                tempArray = [];
                charCount = 0;
            }
        }
    }

    //push whatever remains is in tempArray to the final array.
    if (tempArray.length)
        finalArray.push(tempArray);

    document.write(JSON.stringify(finalArray))

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

Is there a way to retrieve a numerical value from within two specific elements when web scraping?

I am new to web scraping and looking to extract the numbers located between the strong tags. Currently, I am using Python 3.8 along with BeautifulSoup for this task. <li class="price-current"> <span class="price-current-label"> </s ...

The identifier variable fails to function as a reference when I attempt to utilize it

var lightcount = 0; $("#addlight").click(function(){ var domElement = $('<div id="L' + lightcount +'" class="col-md-3 col-sm-6 text-center"><div class="rumbox"></div><button id="onoff" type="button" c ...

What is the best way to iterate through states within an array using React?

Can someone help me create a button that can cycle through different states in the given array? I want the button to change State_1 to State_2, State_2 to State_3, and then back to State_1 for each object. I'm struggling to figure out how to cycle thr ...

How to toggle tooltip visibility dynamically using Angular 2

I am working with elements within an ngFor loop. Some of these elements have tooltips, while others do not. I am experiencing an issue where when using the code snippet below: <div ngFor="let item of items"> <div [title]="item.title"> Ele ...

Memory Exhausted: MongoDB and JavaScript running out of memory

Dealing with a massive amount of data in the telemetry table is proving to be a challenge. I keep encountering the dreaded "JavaScript heap out of memory" error. How can I tackle this issue? const connectionUrl = `mongodb://${userName}:${pwd}@${host}:${ ...

Adjust the button's width as the text changes to create a dynamic animation

I'm trying to create an animation effect where the width of a button changes whenever the text inside it is updated. I've attempted using useRef on the button itself to grab its clientWidth and then applying that value to a CSS variable in order ...

Linking a 2-dimensional array to a Data Table

My current dilemma involves populating a 2D array from two fields in my database. I'm struggling with assigning a value from a database field to an array, as well as displaying the array in a datagrid. Despite coding dgv2.Datasource = myArray, I keep ...

When using selenium with python, the function excecute_script('return variable') may not technically return variables, even though the variable does exist

My attempt to retrieve a variable from javascript code using selenium is encountering difficulties. Despite the presence of the variable (confirmed by inspecting the source code before executing the script), the command driver.execute_script('return v ...

Is it not recommended to trigger the 'focusout' event before the anchor element triggers the 'click' event?

In a unique scenario, I've encountered an issue where an anchor triggers the 'click' event before the input field, causing it to lose focus and fire the 'focusout' event. Specifically, when writing something in the input field and ...

Having trouble installing memlab using the npm package

Recently, I made an attempt to install the memlab library from Meta's GitHub. Initially, when I installed it without using the -g flag, the installation was successful. However, I encountered an issue where I could not execute any of the memlab comman ...

Determining Visibility in Three.js: A Guide to Checking if an Object is in View of the Camera

Struggling to determine the best method for checking if an Object3d is visible to the camera. Imagine a sphere in the center of the screen with cubes randomly placed on its surface. I need a way to identify which cubes are visible (on the front half of th ...

Having trouble getting the Vue.js Element-UI dialog to function properly when embedded within a child component

Take a look at the main component: <template lang="pug"> .wrapper el-button(type="primary", @click="dialogAddUser = true") New User hr // Dialog: Add User add-edit-user(:dialog-visible.sync="dialogAddUser") </template> <s ...

What is the best way to combine the average hours, minutes, seconds, and milliseconds in JavaScript?

I am seeking guidance on how to calculate the average of three different times in JavaScript. In the scenario presented below, the average of the three times is calculated as 01:42:22:566. <form action="/action_page.php"> <label for= ...

Whoops! The input buffer seems to be containing an image format that is not supported while attempting to utilize Next JS next-opt

I initially used the default Image Optimization component in my Next JS app, only to realize that the site could only be hosted on Vercel and not on other web hosting platforms. This limitation prompted me to explore the next-optimized-images package, whic ...

Is it necessary to generate arrays for both even and odd numbers?

Is there a way to change the code below so that it displays even numbers on the first line and odd numbers on the second? #include <stdlib.h> #include <stdio.h> int i,j; int array_1[10]; int main() { for(i=0;i<10;i++) { printf(&quo ...

Performing a password-protected JavaScript Ajax request that includes special characters

Within my JavaScript page, I have implemented an Ajax call shown in the code snippet below. The PHP page resides within a corporate intranet that demands domain authentication (without basic auth). To extract the username (u) and password (p), I am using j ...

Converting varchar to array in Presto Athena: Step-by-step guide

I have data stored in the VARCHAR format and I need to split the array elements in order to extract a key value from the JSON. Data structure [ { "skuId": "5bc87ae20d298a283c297ca1", "unitPrice": 0, "id" ...

Extracting precise information from a JSON file using Angular's $http.get

I am struggling with extracting a specific user from a JSON file containing a user list and displaying it on an Angular index page. Despite extensive research, I have been unable to find a satisfactory solution. The user list must remain in a JSON file ins ...

Stay dry - Invoke the class method if there is no instance available, otherwise execute the instance method

Situation When the input is identified as a "start", the program will automatically calculate the corresponding "end" value and update the page with it. If the input is an "end", simply display this value on the page without any modifications. I am in th ...

Determine the total accumulation of time entities in VueJS

My task involves working with an array of time objects that users will add. The array comprises values like this, with a generic example of "01:01:01" for each date value. let timeObjects = ["01:01:01", "01:01:01", "01:01:01"]; The goal is to iterate thro ...