6
I have the code below 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;
}
Such a 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 one but with the following change:
The last key of the previous group should 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 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?
how it would look if var meuArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; and if var meuArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
– Tiago Gomes
The penultimate group in the case would be [9, 10, 11] and the last would be [11, 1]
– Leo Letto
If you had 12 keys the penultimate would be [9, 10, 11] and the last would be [11, 12, 1]
– Leo Letto