Split Array of items into N Arrays in JavaScript


We are required to write a JavaScript function that splits an Array of numbers into N groups, which must be ordered from larger to smaller groups.

For example, in the below code, split an Array of 12 numbers into 5 Arrays, and the result should be evenly split, from large (group) to small:

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

The function should take in the array as the first argument and the number of partitions as the second argument.

Example

The code for this will be −

const arr = [1,2,3,4,5,6,7,8,9,10,11,12];
const chunkArray = (arr = [], chunkCount) => {
   const chunks = [];
   while(arr.length) {
      const chunkSize = Math.ceil(arr.length / chunkCount−−);
      const chunk = arr.slice(0, chunkSize);
      chunks.push(chunk);
      arr = arr.slice(chunkSize);
   };
   return chunks;
};
console.log(chunkArray(arr, 5));

Output

And the output in the console will be −

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ], [ 9, 10 ], [ 11, 12 ] ]

Updated on: 21-Nov-2020

631 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements