First, if you want to iterate through the amount of months the user types, you don’t have to make this whole complication of [...Array(etc)].forEach(etc)
. Just make a for
simple, starting from index 1 (since you pass i + 1
for the function, then do the loop with the correct values, because then you do not need to add 1, and it is even easier to understand and maintain, in my opinion).
Finally, you can use the method concat
to concatenate the arrays returned to each call:
let meses = // quantidade de meses que o usuário digitar
let resultado = [];
for (let i = 1; i <= meses; i++) {
resultado = resultado.concat(this.getItems(i));
}
It is worth noting that concat
does not modify the original array. Instead, it returns a new array with the result of the concatenation, so I need to assign the return to a variable - in this case, I’m using the same, so at the end of the loop, resultados
will have all the results of getItems
concatenated into a single array.
Example:
function getItems(i) { // retorna um array qualquer
return [ {Id: i, Title: 'X' + i}, {Id: i + 1, Title: 'Y' + i} ];
}
// número de meses
let meses = 4;
let resultado = [];
for (let i = 1; i <= meses; i++) {
resultado = resultado.concat(getItems(i));
}
console.log(resultado);
Another alternative is to use push
, passing the return of getItems
using the syntax of spread (the 3 points ...
, which expands the returned array, causing each element of it to be passed as an argument to push
, what causes them to be added in the array resultado
):
let resultado = [];
for (let i = 1; i <= meses; i++) {
resultado.push(...this.getItems(i));
}