How could I detect if there is more than 1 of the same strings in a table?

Question is as said in the title, how could I detect if there is more than 1 of the same strings in a table?

2 Likes

You can sort the table of strings. This causes similar terms to be grouped together. This way, you can check if the next string is the same as the current string:

local list = {"a", "b", "c", "d", "a", "b"}
table.sort(list)
print(list) --> {"a", "a", "b", "b", "c", "d"}
--[[
    Notice how it's sorted alphabetically now, with similar terms next
    to each other. We can use this to our advantage
--]]

for index, str in ipairs(list) do --> going through the list
    if list[index + 1] == str then --> checking if the next value is the same as [str]
        print(str ... " is a duplicate")
    end
end

@Proville6 The solution provided in the reply only checks if there’s the specified duplicate string. It does not check for any other strings. If there is a duplicate that isn’t hello!, it won’t be detected.

3 Likes

I’d suggest using a dictionary to keep track of this:

local list = {"a","a","b","a","c","b","d","e","a"}
local dict = {}
for i = 0, #list do
	local element = list[i]
	if dict[element] == nil then
		dict[element] = 1
	else
		dict[element] += 1
	end
end
--now we have a dictionary of all of our strings and their counts, so we could do something like:
print(dict["a"]) -- -> 4
--or better, print out a list of all strings and their counts
for k,v in pairs(dict) do
	print(k,v)
end
--[[
a 4
b 2
c 1
d 1
e 1
]]
-- and I guess to answer the question in the title, just do something like this:
local hasDuplicate = false
for k,v in pairs(dict) do
	if v >= 2 then
		hasDuplicate = true
		break
	end
end
print(hasDuplicate) -- -> true
4 Likes

a condensed version

local function isThereDupeString(t :{string})
	local temp = {}
	for _,v in pairs(t) do
		if temp[v] then return true, v end
		temp[v] = ":}"
	end
	return false
end
3 Likes