Count occurence of data in array

2020-02-15 09:13发布

问题:

I have an array like this:

OptiPlex 790
Precision WorkStation T7500
Precision WorkStation T7400
Precision T1500
Precision WorkStation T3500
CELSIUS R650
VMware Virtual Platform
Precision T1500
OptiPlex GX620

I want to get the count of array and will add that in new array.

Element:Count
OptiPlex 790 1 
Precision WorkStation T7500 1 
Precision WorkStation T7500 1

I want to store this value in new array. So, i will use it later/somewhere else.

$array = @()
for ($i=1; $i -le $rowMax-1; $i++) {
    $Model = $sheet.Cells.Item($rowModel+$i, $colModel).text
    Write-Host ("I am reading data on row: " + $i)
    $array += $Model
}

$array | Group

At the moment above script is working fine but I don't know how I can add this data to new array.

回答1:

I would construct a hash table rather than an array:

$Models = @(
  'OptiPlex 790'
  'Precision WorkStation T7500'
  'Precision WorkStation T7400'
  'Precision T1500'
  'Precision WorkStation T3500'
  'CELSIUS R650'
  'VMware Virtual Platform'
  'Precision T1500'
  'OptiPlex GX620'
)

# Create a hashtable
$ModelCount = @{}

# Iterate over each entry in the array, increment value count in hashtable
$Models |ForEach-Object { $ModelCount[$_]++ }

Now your hash table countains all the information you need:

PS C:\> $ModelCount

Name                           Value
----                           -----
OptiPlex 790                   1
VMware Virtual Platform        1
Precision WorkStation T7500    1
Precision T1500                2
CELSIUS R650                   1
Precision WorkStation T7400    1
OptiPlex GX620                 1
Precision WorkStation T3500    1

And you can easily add new values:

# Let's say you found another 3 OptiPlex GX620 somewhere:
$ModelCount['OptiPlex GX620'] += 3

and entries:

$ModelCount['New Model']++

And you can still iterate over it:

PS C:\> $ModelCount.Keys |Sort-Object |ForEach-Object {
>>>     Write-Host "We have $($ModelCount[$_]) of $_ in stock"
>>> }
We have 1 of CELSIUS R650 in stock
We have 1 of OptiPlex 790 in stock
We have 4 of OptiPlex GX620 in stock
We have 2 of Precision T1500 in stock
We have 1 of Precision WorkStation T3500 in stock
We have 1 of Precision WorkStation T7400 in stock
We have 1 of Precision WorkStation T7500 in stock
We have 1 of VMware Virtual Platform in stock


回答2:

There is a Group-Object cmdlet which you can use for that:

$array | group | select Name, Count

Output:

Name                        Count
----                        -----
OptiPlex 790                    1
Precision WorkStation T7500     1
Precision WorkStation T7400     1
Precision T1500                 2
Precision WorkStation T3500     1
CELSIUS R650                    1
VMware Virtual Platform         1