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 −


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);
         acc[currentRow] = [val];
      return acc;
   }, []);
console.log(splitArray(arr, 2));


The output in the console will be −

[ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ]

Updated on: 26-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started