1

Assuming I have an integer n which is greater than 0, and an array like this:

var array = [1, 2, 5, 6, 8, 9, 12, 13, 17...] //random values

How would I iterate through this array, going through and getting values n at a time (and putting it into a 2D array as well)?

If n were 3, for example, I would want a return value of

[[1, 2, 5], [6, 8, 9], [12, 13, 17]...]

And the code would be like this:

var array = [];
for (var i = 0; i < array.length; i += 3) {
    var first = array[i];
    var second = array[i+1];
    var third = array[i+2];

    array.push([
        first, second, third
    ]);
}

Problem with this is that I have fixed values to get my objects by (the i, i+1, etc.)

If I have an unknown integer, then incrementing right up to n will not work.

How would I go about achieving this?

Mingle Li
  • 1,322
  • 1
  • 15
  • 39

1 Answers1

1

Use slice to take chunks and go through the array:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

const partition = (n, arr) => {
  const result = [];
  let i = 0;
  
  while(i < arr.length) {
    result.push(arr.slice(i, i + n));
    i = i + n;
  }
  
  return result;
};

console.log(partition(1, arr));
console.log(partition(2, arr));
console.log(partition(3, arr));
console.log(partition(4, arr));
klugjo
  • 19,422
  • 8
  • 57
  • 75