- 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
Splitting an array into groups in JavaScript
We are required to write a JavaScript function that takes in an array of literals and a number and splits the array (first argument) into groups each of length n (second argument) and returns the two-dimensional array thus formed.
If the array and number is −
const arr = ['a', 'b', 'c', 'd']; const n = 2;
Then the output should be −
const output = [['a', 'b'], ['c', 'd']];
Example
Let us now write the code −
const arr = ['a', 'b', 'c', 'd']; const n = 2; const chunk = (arr, size) => { const res = []; for(let i = 0; i < arr.length; i++) { if(i % size === 0){ // Push a new array containing the current value to the res array res.push([arr[i]]); } else{ // Push the current value to the current array res[res.length-1].push(arr[i]); }; }; return res; }; console.log(chunk(arr, n));
Output
And the output in the console will be −
[ [ 'a', 'b' ], [ 'c', 'd' ] ]
Advertisements