Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Powershell, how can i count the occurrence of each element in an array?

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

like image 882
speedreeder Avatar asked Sep 28 '12 13:09

speedreeder


People also ask

How do you count occurrence of an element in an array?

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 .

How do I count items in an array PowerShell?

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.

How do you count occurrences of each element in an array using HashMap?

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.

How do I count items in PowerShell?

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.


2 Answers

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 }
like image 176
Joey Avatar answered Oct 06 '22 19:10

Joey


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
like image 41
Shay Levy Avatar answered Oct 06 '22 17:10

Shay Levy