Number of elements in an array
How i can know how many elements of certain type are in an array?
For example my_array = ['cat', 'dog', 'cat']
and i want to know that there are: 2 'cat' and 1 'dog'
How i can know how many elements of certain type are in an array?
For example my_array = ['cat', 'dog', 'cat']
and i want to know that there are: 2 'cat' and 1 'dog'
to search for a specific element and count it you can use:
List.count = function(element)
// return the times 'element' appears in List
local c = 0
for i in this
if i == element then c += 1 end
end
return c
end
and the call my_array.count('cat')
returns 2
to search for all elements in the list and count them:
List.countAll = function()
// return an object with the elements of List and their count
local c = object end
for i in this
c[i] += 1
end
return c
end
my_array.countAll()
returns:
object
cat = 2
dog = 1
end
note that you can compere only numbers and strings
Thanks