-1

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]))
0009laH
  • 1,960
  • 13
  • 27
  • Does "[Split Array into chunks](https://stackoverflow.com/questions/8495687/split-array-into-chunks)" answer the question? If not, please could you explain where you're stuck, or how your problem is different? I feel like I'm perhaps misunderstanding "*I want to do consecutive subarrays with size k*." – David Thomas Jan 30 '23 at 17:27
  • @DavidThomas it didn't work for me. the codes below yep – Kerpen rodrigo rosa de miranda Jan 30 '23 at 20:27

2 Answers2

1

Increment the index by the subarray size each time, then slice that number of elements from the current index on each iteration.

function ub(arr, k) {
  let res = [];
  for (let i = 0; i < arr.length; i += k) res.push(arr.slice(i, i + k));
  return res;
}
console.log(JSON.stringify(ub([1,2,3,4,5,6,7,8,9], 3)));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

You can use this way

function ub(a) {
  return a.reduce((acc, val, index) => {
    if (index % 3 === 0) {
      acc.push(a.slice(index, index + 3));
    }
    return acc;
  }, []);
}
console.log(JSON.stringify(ub([1, 2, 3, 4, 5, 6, 7, 8, 9])));

or you can use Array.from

function ub(a) {
  return Array.from({ length: Math.ceil(a.length / 3) }, (_, i) =>
    a.slice(i * 3, i * 3 + 3)
  );
}
console.log(JSON.stringify(ub([1, 2, 3, 4, 5, 6, 7, 8, 9])));
I_Al-thamary
  • 3,385
  • 2
  • 24
  • 37