How to do a consecutive subarrays in JavaScript

89 Views Asked by At

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]))
2

There are 2 best solutions below

0
Unmitigated On

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)));

0
I_Al-thamary On

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])));