astrasleepz
astrasleepz

Reputation: 404

How to create multidimensional array / array tree from list of array?

I have an array of:

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

The task is to make array within an array for combined 10 character length which in this case would be something like this:

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

I tried to do this:

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]);
    }
    // ...
}   

But then it will push it back to the same order as before since I am only pushing each iteration that passed the condition. I have no clue as to how to make the multidimensional array as above. Any help would be appreciated. Thanks!

Upvotes: 0

Views: 80

Answers (6)

Shadowind
Shadowind

Reputation: 114

This solution does not cater for:

  1. The input array not being in the correct order, so as to ensure a complete pairing of 10 characters, for example it will not work with an input array of ["hello", "whatever"].
  2. It does not cater for the conditional splitting of an array item into two separate arrays. For Example ["hello", "whatever"] = [["hello", "whate"],["ver"]]

So with the information supplied you can try this:

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))

Upvotes: 0

trincot
trincot

Reputation: 351084

Here is a corrected version of your code:

var arr = ["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"];
var combArr = [];
var charCount = 0;
var currArr = []; // ADDED: the current list of words 

for (i = 0; i < arr.length; i++) {
    if (charCount && (charCount + arr[i].length > 10)) {
        // save list
        combArr.push(currArr);
        // ... and start new list
        currArr = [];
        charCount = 0;
     }
     charCount += arr[i].length;
     currArr.push(arr[i]);
}   
// finally add remaining list to result:
combArr.push(currArr);

Upvotes: 1

K&#252;rşat
K&#252;rşat

Reputation: 99

Try this; (edited)

 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))

Try this;

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))

Upvotes: 0

le_m
le_m

Reputation: 20248

You can fix your code by adding one more level of nesting to your combArr, resetting your charCount for each new 'row' and handling the case when the first entry of arr is longer than 10 characters by appending || i == 0 to your 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 performant solution is:

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"]));

Upvotes: 0

dlopez
dlopez

Reputation: 995

You can try with something like this.

var arr = ["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"];
var MAX_LENGTH = 10;
var finalArray = arr.reduce(function(prev, curr) {
  if (prev.length === 0) {
    prev.push([curr]);
  } else {
    var currentItemLength = prev[prev.length-1].reduce(function(iprev, icurr) {
      return iprev + icurr.length;
    }, 0);
    if (currentItemLength + curr.length > MAX_LENGTH) {
      prev.push([curr]);
    } else {
      prev[prev.length-1].push(curr);
    }
  }
  return prev;
}, []);
console.log(finalArray)

Upvotes: 0

Jake Haller-Roby
Jake Haller-Roby

Reputation: 6427

The main thing you're missing; You need to create new arrays, and then push those multiple arrays into a parent array.

An example, to get you going;

var container = [];
var child1 = [];
var child2 = [];

child1.push("foo");
child1.push("bar");

child2.push("baz");

container.push(child1);
container.push(child2);

console.log(container); // [["foo", "bar"], ["baz"]]

I'll leave the conditional logic of the problem at hand to you, but this should get you past that hurdle. Good luck!

Upvotes: 1

Related Questions