Using Powershell, how can i count the occurrence of each element in an array?
Joey's helpful answer provides the crucial pointer: use the Group-Object
cmdlet to group input objects by equality.
(To group them by one ore more of their property values instead, use -Property
).
Group-Object
outputs [Microsoft.PowerShell.Commands.GroupInfo]
objects that each represent a group of equal input objects, whose notable properties are:
.Values
... the value(s) that define the group, as a[System.Collections.ArrayList]
instance (which has just 1 element in the case at hand, since the input objects as a whole are used to form the groups)..Count
... the count of objects in that group.
If, as in this case, there is no need to collect the individual group members as part of each group, -NoElement
can be used for efficiency.
You're free to further process the group objects as needed; to get the specific output format stipulated in your question, you can use Select-Object
with a calculated property.
To put it all together:
PS> 1, 1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 5 | Group-Object -NoElement |
Select-Object @{ n='Element:Count'; e={ '{0}:{1}' -f $_.Values[0], $_.Count } }
Element:Count
-------------
1:3
2:2
3:1
4:4
5:2
You can adjust the output and format it as you like:
PS> $ht= 1,1,1,2,2,3,4,4,4,4,5,5 | Group-Object -AsHashTable -AsString
PS> $ht
Name Value
---- -----
2 {2, 2}
4 {4, 4, 4, 4}
5 {5, 5}
1 {1, 1, 1}
3 {3}
PS> $ht['1']
1
1
1
You can use the Group-Object
cmdlet:
PS> 1,1,1,2,2,3,4,4,4,4,5,5 | group
Count Name Group
----- ---- -----
3 1 {1, 1, 1}
2 2 {2, 2}
1 3 {3}
4 4 {4, 4, 4, 4}
2 5 {5, 5}
If you want a hashtable for the items and their counts you just need a little ForEach-Object
after it:
$array | group | % { $h = @{} } { $h[$_.Name] = $_.Count } { $h }