
- 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
Chunking array within array in JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first argument and a single number, say num, as the second argument. Num will always be less than or equal to the length of the array.
The function should prepare a new array that must contain num number of subarrays. All the subarrays should contain equal number of arrays if length of array is exactly divisible by num otherwise only the last subarray should contain different number of elements.
For example −
If the input array and the number are −
const arr = [1, 2, 3, 4, 5, 6, 7, 8]; const num = 3;
Therefore, the output for the above input should look like this −
const output = [ [1, 2, 3], [4, 5, 6], [7, 8] ];
Example
The code for this will be −
const arr = [1, 2, 3, 4, 5, 6, 7, 8]; const num = 3; const chunkArray = (arr = [], num = 1) => { const { length: l } = arr; const elPerArr = Math.ceil(l / num); const res = arr.reduce((acc, val, ind) => { const curr = Math.floor(ind / elPerArr); if(!acc[curr]){ acc[curr] = [val]; }else{ acc[curr].push(val); } return acc; }, []); return res; }; console.log(chunkArray(arr, num));
Output
And the output in the console will be −
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ]
- Related Questions & Answers
- Chunking an array in JavaScript
- Chunking arrays in JavaScript
- Filtering array within a limit JavaScript
- Find average of each array within an array JavaScript
- Find average of each array within an array in JavaScript
- Number of vowels within an array in JavaScript
- Sum identical elements within one array in JavaScript
- Finding confusing number within an array in JavaScript
- Counting possible APs within an array in JavaScript
- Sum similar numeric values within array of objects - JavaScript
- Finding the third maximum number within an array in JavaScript
- How to check whether multiple values exist within a JavaScript array
- How to redundantly remove duplicate elements within an array – JavaScript?
- Delete specific record from an array nested within another array in MongoDB?
- Deleting specific record from an array nested within another array in MongoDB
Advertisements