chunk

function chunk( arr, size ) --> chunks

Description

Creates an array table of elements split into groups the length of size. If arr can’t be split evenly, the final chunk will be the remaining elements.

Parameters

arr

The array table that should be split into chunks.

size

The maximum size of the sub-arrays.

Return Values

chunks

A array table with the chunks.

Code

--ZFUNC-chunk-v1
local function chunk( arr, size )
   local chunks = {}

   local full_packs = math.floor( #arr / size )
   for i = 1, full_packs do
      local sub = {}
      local b = ( i * size ) - ( size - 1 )
      local e = i * size
      for idx = b, e do
         table.insert( sub, arr[ idx ] )
      end
      table.insert( chunks, sub )
   end

   return chunks
end

return chunk

Examples

local t = require( "taptest" )
local chunk = require( "chunk" )
local same = require( "same" )

local res = chunk( { "a", "b", "c", "d", "e", "f" }, 3 )

t( #res, 2 )
t( same( res[ 1 ], { "a", "b", "c" } ), true )
t( same( res[ 2 ], { "d", "e", "f" } ), true )

t()

Inspired by