

- 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
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 ] ]
- Related Questions & Answers
- Split number into n length array - JavaScript
- Split tuple into groups of n in Python
- Can split array into consecutive subsequences in JavaScript
- JavaScript Converting array of objects into object of arrays
- Converting array of arrays into an object in JavaScript
- Split one-dimensional array into two-dimensional array JavaScript
- Combine unique items of an array of arrays while summing values - JavaScript
- Turning a 2D array into a sparse array of arrays in JavaScript
- Split string into groups - JavaScript
- Split Array by part base on N count in JavaScript
- Split Array into Consecutive Subsequences in C++
- How can we make an Array of Objects from n properties of n arrays in JavaScript?
- How to combine two arrays into an array of objects in JavaScript?
- Splitting array of numbers into two arrays with same average in JavaScript
- Split string into equal parts JavaScript
Advertisements