1

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?

4
  • Please show us the code with which you define the array and assign the values. Answer may differ based on whether it's an actual multidimensional array, a jagged/nested array or a flat array of objects Commented Feb 28, 2018 at 21:33
  • It is a pretty basic array. It is populated within a loop and looks something like this: $myArray += ,($year, $amount) Commented Feb 28, 2018 at 21:39
  • Create a hashtable? Commented Feb 28, 2018 at 21:59
  • I've been trying, but my PS skills clearly aren't there yet :( Commented Feb 28, 2018 at 22:05

2 Answers 2

2

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))
}
Sign up to request clarification or add additional context in comments.

1 Comment

@BjørnH.Sandvik: My pleasure; glad it was helpful.
0

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"

2 Comments

I very much appreciate the approach, but the array may contain any number of different years in the first element. I am looking for a way to handle this variety dynamically..
In SQL-speak, what I am looking for is akin to SELECT SUM(COLUMN2) GROUP BY COLUMN1 ORDER BY COLUMN1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.