I am studying algorithms in JavaScript; I am trying to generate consecutive subarrays but I don't know to do it.
I have the following array:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
I want to split it in subarrays of size 3 using iteration:
[1, 2, 3] [4, 5, 6] [7, 8, 9]
I know how to do a subarray using slice()
, but as I told I want to do consecutive subarrays with size k.
function ub(a) {
let resposta = []
for (let i = 0 ; i < a.length; i++) {
resposta = a.slice(2, 5)
}
return resposta
}
console.log(ub([2, 37, 8, 9, 23, 34, 44]))