Split array into smaller groups

Asked

Viewed 3,614 times

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 so:

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.

  • Because it can vary, then the rule should be better explained, what is the true rule of creating multiple arrays from one?

  • The cut will be made according to the amount of results that fit in user resolution, if it is 5 I will cut 5 in 5 and create a line with these 5 and so on

  • If the item number is 6 as it is divided?

  • That’s what I want to know, if it’s 6 by 6, I’m going to upgrade the division inside the sucess and pass the loop that someone will answer me, I’m going to test with the current answers to see if I can get what I want.

5 answers

7

You can use the method Array#Slice that will divide 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 full 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 than 5, the new array will be cut. The last array will be left with the rest of the elements.

6


I’d do it this way:

  • It would go through the items of array;

  • Use a variable to control the group the item will be placed in;

  • It would increment the variable if the rest of its division was 0. (In your case in 5, 10, ... 25, ...);

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

With ES6 using Math.floor, reduce and Sintaxe de Espalhamento:

const separar = (itens, maximo) => {
  return itens.reduce((acumulador, item, indice) => {
    const grupo = Math.floor(indice / maximo);
    acumulador[grupo] = [...(acumulador[grupo] || []), item];
    return acumulador;
  }, []);
};

// Teste de execução
const itens = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
console.log(JSON.stringify(separar(itens, 5)));

  • and to access the obtained results? I did this data = JSON.stringify(separate(5)); .

  • @Leoletto dados = separar(5); The JSON.stringify is to turn into string

  • Does this function take into account if meuArray has less than 5 keys? because I tested it here and when there are only 2 keys for example, it returns in the array only of the keys obtained in myArray

  • Thanks, it worked the way I needed it :)

  • 1

    @Leoletto I will make a slight change so that you pass the array as parameter as well. It is more useful.

3

I recommend you take a look at the push method of Array: http://www.w3schools.com/jsref/jsref_push.asp

But a very basic example would be like this:

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

Until the amount you need, recommend using a loop.

1

Using a simple repeat loop, you can use the 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));

-3

If use at multiple points, suggest adding prototypes of objects.

var splitList = function (list, limit) {
  var originalList = [];

  var loop = Number((list.length / limit).toFixed(0)) + (!!(list.length % limit) ? 1 : 0);
      
  for (var index = 0, position = limit; index < loop; index++, position += limit) {
    var grup = list.slice(index * limit, position);
    if (grup.length) originalList.push(grup);
  };

  return originalList;
};

console.log(splitList([1,2,3,4,5,6,7], 4)); ///[[1,2,3,4],[5,6,7]]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.