How would I split an array into x amount of arrays?

Given an array of any length, I want a function that takes in said array and an integer for how many splits then it returns the an array with all those new arrays. Something like this:

local function SplitArray(array, splits)
    -- code
    return arrays
end

Thanks for any help, I am finding it tricky to get this to work.

2 Likes
2 Likes

From what I see you’re trying to convert an array into a 2D array. I was able to create what you described, this is what it would look like:

Arr = {1, 2, 3, 4, 5, 6, 7} -- Sample array

function ArrayFragment(Array, Amount)
	local amt = math.ceil(#Array/Amount) --The amount of fragments in the 2D array
	local length = math.ceil(#Array/amt) -- The amount of objects in each fragment
	local Array2 = {}
	for i = 1, amt, 1 do -- Fill the 2D array with blank arrays
		Array2[i] = {}
	end
	local count = 0 -- Initialize a counter variable
	for i = 1, #Array2, 1 do
		for j = 1, length, 1 do -- Populate the fragments with values from the original array with index of the counter variable value
			count += 1
			Array2[i][j] = Array[count]
		end
	end
	return Array2
end

print(ArrayFragment(Arr, 4)) -- Sample output

What this does is, in a function, initializes a 2D array based on the amount of fragments you want, and fills those fragments with elements of the original array fed to the function as the parameter.

1 Like

Thanks for the help, but I rather do this as it loops only once.

function tableSplit(t, splits)
	splits = #t/splits

    local insert = table.insert
    local move = table.move
    local result = {}

    local tn
	for i = 1, #t, splits do
		tn = {}
		insert(result, tn)
		move(t, i, i + splits, 1, tn)
	end

	return result
end