Transform a Normal Array into Multidimensional

4

I have an array in this format:

meuArray = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ...];

I would like to turn it into a multidimensional array with javascript / jquery leaving it like this:

meuArray = [
             [0] => ["0", "1", "2", "3", "4"];
             [1] => ["5", "6", "7", "8", "9"];
              ...
           ]

The number of keys per array will vary, but for ease of response, we can always consider 5 keys per array.

    
asked by anonymous 24.11.2016 / 12:57

4 answers

6

I would do it as follows:

  • I would browse the items of array ;

  • I would use a variable to control the group where the item will be placed;

The result is as follows:

var arrayBase = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var dados = [];

function separar(base, maximo) {
  var resultado = [[]];
  var grupo = 0;

  for (var indice = 0; indice < base.length; indice++) {
    if (resultado[grupo] === undefined) {
      resultado[grupo] = [];
    }

    resultado[grupo].push(base[indice]);

    if ((indice + 1) % maximo === 0) {
      grupo = grupo + 1;
    }
  }

  return resultado;
}

dados = separar(arrayBase, 5);
console.log(JSON.stringify(dados));
    
24.11.2016 / 13:10
6

You can use the Array # slice method that will split the array based on the start and end index, iterating the array by a cut value, taking into account that its array may have n total size.

var meuArray = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
  , novoArray = []
  , corte = 5;

for (var i = 0; i < meuArray.length; i = i + corte) {
  novoArray.push(meuArray.slice(i, i + corte));
}

console.log(novoArray);

Even if the array has another size or cut other than 5, the new array will be cut. The last array will have the rest of the elements.

    
24.11.2016 / 13:06
3

I recommend you take a look at the Array push method: link

But a very basic example would look like this:

meuArray = [];
meuArray.push([1, 2, 3, 4, 5]);
meuArray.push([6, 7, 8, 9, 10]);

Until the amount you need, I recommend using a loop.

    
24.11.2016 / 13:00
1

Using a simple loopback, you can use Array.Slice to separate the array and the < Array.Push to create a new one with the extracted elements.

function separarArray(arr, tamanho) {
  var novoArray = [];
  var i = 0;
  while (i < arr.length) {
    novoArray.push(arr.slice(i, i + tamanho));
    i += tamanho;
  }
  return novoArray;
}

console.log(separarArray(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], 5));
    
24.11.2016 / 14:08