javascript – Split an array into groups?

Question:

I have the code below answered by a question similar to this one but I would like to upgrade, this is the current function:

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

Such a function will separate a common array into a multidimensional one of groups, according to the number of keys per group that is specified in maximo , but now I need a function similar to the same but with the following change:

The last key of the previous group must be the first of the next group to be generated.

For example:

var meuArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
/*separo meu array em grupos de 3 chaves*/
console.log(separar(meuArray, 3));

The example above should print:

   [
      0: [1, 2, 3]
      1: [4, 5, 6]
      2: [7, 8, 9]
      3: [10]
   ]

With the change I would like it to print the array as follows:

   [
      0: [1, 2, 3]
      1: [3, 4, 5]
      2: [5, 6, 7]
      3: [7, 8, 9]
      4: [9, 10, 1]
   ]

In the last group I already include the first key of the next group, how can I do that?

Answer:

You can optimize the function a little using Array#slice .

Result:

function separar(base, max) {
  var res = [];
  
  for (var i = 0; i < base.length; i = i+(max-1)) {
    res.push(base.slice(i,(i+max)));
  }
  res[res.length-1].push(base[0]);
  return res;
}

var meuArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
/*separo meu array em grupos de 3 chaves*/
console.log(separar(meuArray, 3));
.as-console-wrapper {top: 0; max-height: 100%!important}

The idea is to "cut" the array by parts, but if the group is not first cut from the previous index with respect to the current position and finally add the first index of the source array to the last of the result array.

Scroll to Top