Bjørn H. Sandvik
Bjørn H. Sandvik

Reputation: 543

PowerShell foreach() multidimensional array based on first element

I have a fairly basic multidimensional array which looks something like this:

2017,123 
2017,25
2018,5
2018,60
2017,11

I wish to run a ForEach() loop or similar function to total the numbers in the second element based on the year indicated in the first so that I end up with an output like this:

2017,159
2018,65

How do I best accomplish this?

Upvotes: 1

Views: 3159

Answers (2)

mklement0
mklement0

Reputation: 437588

The following solution is concise, but not fast:

# input array
$arr = 
  (2017,123),
  (2017,25),
  (2018,5),
  (2018,60),
  (2017,11)

# Group the sub-arrays by their 1st element and sum all 2nd elements
# in each resulting group.
$arr | Group-Object -Property { $_[0] } | ForEach-Object {
  , ($_.Name, (($_.Group | ForEach-Object { $_[1] } | Measure-Object -Sum).Sum))
}

Upvotes: 2

qbanet359
qbanet359

Reputation: 193

Assuming your array looks like "$array" this will give you what you need:

$2017total = 0
$2018total = 0

$array = "2017,123",
"2017,25",
"2018,5",
"2018,60",
"2017,11" | % { 

if ($_ -match '2017') {
    $2017 = ($_ -split ',')[1]
    $2017total += $2017
}
else {
    $2018 = ($_ -split ',')[1]
    $2018total += $2018
} 
}

Write-Host "2017,$2017total"
Write-Host "2018,$2018total"

Upvotes: 0

Related Questions