0

How do I convert Array to an Array of Arrays by specifying a width?

Input: Array [1,2,3,4,5,6,7]  and Width = 3

Output: Array [[1,2,3],[4,5,6], [7]]

I am sure I can do programmatically however looking for an optimized/ using inbuilt functions if any.

javapedia.net
  • 2,531
  • 4
  • 25
  • 50

1 Answers1

1

For future reference, what you are looking for is called "chunking".

Here's a reference implementation from the popular library lodash:

function chunk(array, size = 1) {
  size = Math.max(toInteger(size), 0)
  const length = array == null ? 0 : array.length
  if (!length || size < 1) {
    return []
  }
  let index = 0
  let resIndex = 0
  const result = new Array(Math.ceil(length / size))

  while (index < length) {
    result[resIndex++] = slice(array, index, (index += size))
  }
  return result
}
Slava Knyazev
  • 5,377
  • 1
  • 22
  • 43
  • 1
    It really is better to flag duplicate content, instead of answering them, to avoid cluttering the site. – Blue Jun 23 '23 at 00:39