Chunking an array in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a function chunk() that takes in an array arr of string / number literals as the first argument and a number n as second argument.

We are required to return an array of n subarrays, each of which contains at most arr.length / n elements. And the distribution of elements should be like this −

The first element goes in the first subarray, second in second, third in third and so on. Once we have one element in each subarray, we again start with filling the first subarray with its second element. Similarly, when all subarrays have two elements only after that we fill the third element in the first array and so on.

For example −

// if the input array is:
const input = [1, 2, 3, 4, 5, 6];
//then the output should be:
const output = [
   [1, 4],
   [2, 5],
   [3, 6]
];

Let’s write the code for this function, we will Array.prototype.reduce() method over the original array to construct the desired array. The code for this will be −

Example

const input = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunk = (arr, size) => {
   return arr.reduce((acc, val, ind) => {
      const subIndex = ind % size;
      if(!Array.isArray(acc[subIndex])){
         acc[subIndex] = [val];
      } else {
         acc[subIndex].push(val);
      };
      return acc;
   }, []);
};
console.log(chunk(input, 4));

Output

The output in the console will be −

[ [ 1, 5, 9 ], [ 2, 6 ], [ 3, 7 ], [ 4, 8 ] ]
raja
Updated on 25-Aug-2020 07:32:50

Advertisements