Divide one table into multiple arrays every X elements

Viewed 44

suppose i have one table, and i want do subdivide it every X elements

fruits = {"banana","orange","apple","avocado","cherry","coconut"}

 -- Split every 2 elements independent of array size

fruits = {{"banana","orange"},{"apple","avodado"},{"cherry","coconut"}}
1 Answers

use two for loop with step of x

local function splitx(tbl, x)
  assert(x > 0)
  assert(type(tbl) == "table")
  local result = {}
  for i=1,#tbl,x do
    local item = {}
    for j=i,i+x-1 do
      if tbl[j] then
        table.insert(item, tbl[j])
      end
    end
    table.insert(result, item)
  end
  return result
end
Related