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

Example

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
         res.push([arr[i]]);
      }
      else{
         // Push the current value to the current array
         res[res.length-1].push(arr[i]);
      };
   };
   return res;
};
console.log(chunk(arr, n));

Output

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
Advertisements