- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ] ]
Advertisements
To Continue Learning Please Login
Login with Google