If I have an array:
1 1 1 2 2 3 4 4 4 4 5 5
How can I use Powershell to tell me how many of each element there are in that array?
To be a little more clear, I should have a separate count for each array element:
Element:Count
1:3
2:2
3:1
4:4
5:2
To count the occurrences of each element in an array: Declare a variable that stores an empty object. Use the for...of loop to iterate over the array. On each iteration, increment the count for the current element if it exists or initialize the count to 1 .
Use the Count Property to Count the Length of Array in PowerShell. Moreover, Count is an alias for the Length property. You can also use Count to find the length of an array. It is easy to find the number of items stored in an array in PowerShell.
Step 1 : Create one HashMap object called elementCountMap with elements of inputArray as keys and their occurrences as values. Step 2 : Check every element of inputArray for its presence in elementCountMap. Step 3 : If an element is already present in elementCountMap, increment it's count by 1.
You can use Measure-Object to count objects or count objects with a specified Property. You can also use Measure-Object to calculate the Minimum, Maximum, Sum, StandardDeviation and Average of numeric values. For String objects, you can also use Measure-Object to count the number of lines, words, and characters.
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 }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With