Array split into groups of specific length in JavaScript


In this post, I am sharing a few methods of converting 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 a variety of any JavaScript objects.

Array split with Array.splice

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
}

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 this:

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

As you can see, if an array can’t be split evenly, the final group (chunk) will be the remaining elements. Also, the input array stays unmodified.

Array split using iteration

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
}

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 this:

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

As in the previous example, if an array can’t be split evenly, the final group (chunk) will be the remaining elements. Also, the input array stays unmodified.

Array split with Lodash library

A similar split of an array into groups (chunks) of specified length can be performed with one of the standard JavaScript libraries Lodash and its chunk function.

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

That will give you output as follows:

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

Similarly to previous methods, if an array can’t be split evenly, the final group (chunk) will be the remaining elements. Also as in previous examples, _.chunk function returns a new two-dimensional array, leaving input array unmodified.


Tags:

#array #conversion #javascript #lodash #split


You may also be interested in:



comments powered by Disqus