Splitting an array into groups in JavaScript

We are required to write a JavaScript function that takes in an array of literals and a number and splits the array (first argument) into groups each of length n (second argument) and returns the two-dimensional array thus formed.

If the array and number is −

const arr = ['a', 'b', 'c', 'd'];
const n = 2;

Then the output should be −

const output = [['a', 'b'], ['c', 'd']];


Let us now write the code −

const arr = ['a', 'b', 'c', 'd'];
const n = 2;
const chunk = (arr, size) => {
   const res = [];
   for(let i = 0; i < arr.length; i++) {
      if(i % size === 0){
         // Push a new array containing the current value to the res array
         // Push the current value to the current array
   return res;
console.log(chunk(arr, n));


And the output in the console will be −

[ [ 'a', 'b' ], [ 'c', 'd' ] ]

Updated on: 20-Nov-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started