Split Array by part base on N count in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of literals and a number, say n.

The function should return a new array, chunked into n subarrays, given that n will always be less than or equal to the length of the array.

For example: If the input array is −

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

Then the output should be −

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

Example

The code for this will be −

const arr = [1,2,3,4,5,6,7,8,9,10];
const n = 3;
const divideIntoChunks = (arr, count) => {
   const res = [];
   const size = arr.length / count;
   let ind = 0;
   while (ind < arr.length) {
      res.push(arr.slice(ind, ind += size));
   };
   return res;
};
console.log(divideIntoChunks(arr, n));

Output

The output in the console −

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9, 10 ] ]
raja
Published on 10-Oct-2020 08:00:27
Advertisements