In this post, I am sharing how to convert a one dimensional array into a two dimensional array with a specific number of items in second level arrays.

For presentation purposes I will use an array of strings. However, you can use an array of any JavaScript objects.

There are a few examples performing an array conversion.

In the first example I use array.splice() function:

function arrayTo2DArray1 (list, howMany) {
    var result = []; input = list.slice(0); 
    while(a[0]) { 
        result.push(a.splice(0, howMany)); 
    }
    return result;
}

And the following code snippet:

var input = ['a', 'b', 'c', 'd', 'e', 'f', 
             'g', 'h', 'i', 'j', 'k', 'l', 
             'm', 'n', 'o', 'p', 'q', 'r'];
console.log(arrayTo2DArray1(input, 9))

Would give output like:

[ [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' ], 
  [ 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p' ], 
  [ 'q', 'r' ] ]

In the second example I perform iteration over array items:

function arrayTo2DArray2 (list, howMany) {
    var idx = 0; result = [];

    while(idx < list.length) {
        if(idx % howMany === 0) result.push([]);
        result[result.length - 1].push(list[idx++]);
    }

    return result;
}

And the following code snippet:

var input = ['a', 'b', 'c', 'd', 'e', 'f', 
             'g', 'h', 'i', 'j', 'k', 'l', 
             'm', 'n', 'o', 'p', 'q', 'r'];
console.log(arrayTo2DArray2(input, 5))

Would give output like:

[ [ 'a', 'b', 'c', 'd', 'e' ],
  [ 'f', 'g', 'h', 'i', 'j' ],
  [ 'k', 'l', 'm', 'n', 'o' ],
  [ 'p', 'q', 'r' ] ]

Enjoy!