- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 one-dimensional array into two-dimensional array JavaScript
We are required to write a function that takes in a one-dimensional array as the first argument and a number n as the second argument and we have to make n subarrays inside of the parent array (**if possible) and divide elements into them accordingly.
** if the array contains 9 elements and we asked to make 4 subarrays, then dividing 2 elements in each subarray creates 5 subarrays and 3 in each creates 3, so in such cases we have to fallback to nearest lowest level (3 in this case) because our requirement is to distribute equal number of elements in each subarray except the last one in some special cases.
For example −
// if the input array is: const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']; // and the number is 2 //then the output should be: const output = [ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ];
Let’s write the code for this function −
Example
const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']; const splitArray = (arr, rows) => { const itemsPerRow = Math.ceil(arr.length / rows); return arr.reduce((acc, val, ind) => { const currentRow = Math.floor(ind / itemsPerRow); if(!acc[currentRow]){ acc[currentRow] = [val]; }else{ acc[currentRow].push(val); }; return acc; }, []); }; console.log(splitArray(arr, 2));
Output
The output in the console will be −
[ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ]
- Related Articles
- Difference Between One-Dimensional (1D) and Two-Dimensional (2D) Array
- How to split comma and semicolon separated string into a two-dimensional array in JavaScript ?
- Transpose of a two-dimensional array - JavaScript
- Multi-Dimensional Array in Javascript
- Get the Inner product of a One-Dimensional and a Two-Dimensional array in Python
- How to create a two dimensional array in JavaScript?
- Single dimensional array vs multidimensional array in JavaScript.
- Alternating sum of elements of a two-dimensional array using JavaScript
- Java Program to convert array to String for one dimensional and multi-dimensional arrays
- Dimensional Array in C#?
- Merging duplicate values into multi-dimensional array in PHP
- Passing two dimensional array to a C++ function
- Converting multi-dimensional array to string in JavaScript
- Creating a two-dimensional array with given width and height in JavaScript
- How to print one dimensional array in reverse order?

Advertisements