 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
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
 