

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Splitting an array into chunks in JavaScript
We are required to write a function, let’s say 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.
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 = [656, 756, 5345, 67, 43, 76, 54, 768, 34];
And the number n is 3,
Then the output should be −
const output = [ [ 656, 67, 54 ], [ 756, 43, 768 ], [ 5345, 76, 34 ] ];
Therefore, let’s write the code for this function −
We will Array.prototype.reduce() method over the original array to construct the desired array.
Example
The code for this will be −
const input = [656, 756, 5345, 67, 43, 76, 54, 768, 34]; const divideArray = (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(divideArray(input, 3));
Output
The output in the console will be −
[ [ 656, 67, 54 ], [ 756, 43, 768 ], [ 5345, 76, 34 ] ]
- Related Questions & Answers
- Splitting an array into groups in JavaScript
- Splitting an object into an array of objects in JavaScript
- Splitting Number into k length array in JavaScript
- Splitting string into groups – JavaScript
- Splitting a string into parts in JavaScript
- Splitting a string into maximum parts in JavaScript
- Splitting array of numbers into two arrays with same average in JavaScript
- Splitting an array based on its first value - JavaScript
- JavaScript Splitting string by given array element
- How can I convert an array to an object by splitting strings? JavaScript
- Splitting number into n parts close to each other in JavaScript
- Convert JS array into an object - JavaScript
- How to split a vector into chunks in R?
- How to convert an object into an array in JavaScript?
- Converting array to object by splitting the properties - JavaScript