JavaScript program that divides an array into chunks of a specified size
Posted by SceDev
Last Updated: February 24, 2024

Write a JavaScript program that divides an array into chunks of a specified size.

Output:

[

  [ 1, 2 ],   [ 3, 4 ],

  [ 5, 6 ],   [ 7, 8 ],

  [ 9, 10 ],  [ 11, 12 ],

  [ 13, 14 ], [ 15, 16 ],

  [ 17, 18 ], [ 19, 20 ]

]

 

Code:

function arrayChunk(array, size) {
    const result = [];
    for (let i = 0; i < array.length; i += size) {
      result.push(array.slice(i, i + size));
    }
    return result;
  }
  

  const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

  var result = arrayChunk(nums, 2)

  console.log(result);