Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to count how many times an element appears in a table?

Say that I have a table like this:

local table = {"1", "1", "2", "3", "4"}


for i,v in pairs(table) do
	print(v)
end

How would I go about creating a function that counts how many times each item is in the table? For example, it would return 2 for "1", but it would return 1 for the others. Thanks.

1 answer

local table={"1","1","2","3","4"}
local table_count
for i,v in pairs(table) do
	--adding the information from the original table to a count
	if not table_count[i] then
		table_count[i]=1
	else
		table_count[i]+=1
	end
end
--function that will return how many times an object is in the original table.
local function count_returner(identifier)
	if table_count[identifier] then
		return table_count[identifier]
	else
		--[[will return false since there are no instances of the item you are looking for. you can also change this to 0 if you like]]
		return false
	end
end

the above code will work but it is probably a "dumb" way; there are probably more straightforward solutions.

2 comments

0

I think you're suppose to replace "i" with "v".

0

yeah, thanks for catching that

This discussion is preserved as it was. New answers, comments, and votes are closed.