I have the following code answered by a question similar to this 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;
}
This function will separate a common array into a multidimensional group, 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 above example should print:
[
0: [1, 2, 3]
1: [4, 5, 6]
2: [7, 8, 9]
3: [10]
]
With the change I would like you 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 this?