Sorting GetChildren() list to count names

Simply i want to make the GetChildren() function sort list more organized giving me a more detailed list of child values.

for example

[1] Hello
[2] Bye
[3] Hello
[4] Bye
[5] Hello
[6] Hello

[Hello] = 4
[Bye] = 2

I’m sure there is a simple way to achieve this maybe with dictionary and for loops but i can’t get it

here is an example

local childVals = {
[1] = "Hello",
[2] = "Bye",
[3] = "Hello",
[4] = "Bye",
[5] = "Hello",
[6] = "Hello"
}

local Hello = 0
local Bye = 0

for i, v in pairs(childVals) do
   if v == "Hello" then
      Hello += 1
   elseif v == "Bye" then
      Bye += 1
   end
end

print(Hello) -- 4
print(Bye) -- 2

This can be done with a pre-made table but what about for example a model with 200+ more parts? Should you write all the part names?

This is very simple.

  • Create a new table where you want to store the results.
  • Loop through the children and increment the name of the child in the new table.

That was poorly worded, so here’s an example:

local otherTable = {"foo", "foo", "bar", "foo", "bar"}
local count = {}
for _,v in ipairs(otherTable) do
    -- count[v] may be nil.
    count[v] = (count[v] or 0) + 1
end

If otherTable is a table of Instances you might want to replace v with v.Name, if that’s the property you want indexed.

    count[v.Name] = (count[v.Name] or 0) + 1
2 Likes

Ah, if there are a lot then do this
(Nevermind someone already posted)

local childVals = {
   [1] = "Hello",
   [2] = "Bye",
   [3] = "Hello",
   [4] = "Bye",
   [5] = "Hello",
   [6] = "Hello"
}

local valList = {}

for i, v in pairs(childVals) do
   if not valList[v] then 
      valList[v] = 0 
   end 

   valList[v] += 1
end

print(valList)
-- ["Bye"] = 2
-- ["Hello"] = 4
1 Like

Thank you both guys, finally an answer for this problem

1 Like