Chunking array within array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of numbers as the first argument and a single number, say num, as the second argument. Num will always be less than or equal to the length of the array.

The function should prepare a new array that must contain num number of subarrays. All the subarrays should contain equal number of arrays if length of array is exactly divisible by num otherwise only the last subarray should contain different number of elements.

For example −

If the input array and the number are −

const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const num = 3;

Therefore, the output for the above input should look like this −

const output = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8]
];

Example

The code for this will be −

const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const num = 3;
const chunkArray = (arr = [], num = 1) => {
   const { length: l } = arr;
   const elPerArr = Math.ceil(l / num);
   const res = arr.reduce((acc, val, ind) => {
      const curr = Math.floor(ind / elPerArr);
      if(!acc[curr]){
         acc[curr] = [val];
      }else{
         acc[curr].push(val);
      }
      return acc;
   }, []);
   return res;
};
console.log(chunkArray(arr, num));

Output

And the output in the console will be −

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ]
raja
Published on 25-Nov-2020 11:46:49
Advertisements