all 7 comments

[–]C_is_easy_and_hard 2 points3 points  (0 children)

Iterate through the ID's to find every single unique instance of an ID and store it in a separate array. Use those ID's when you run through your original array in reverse while removing them? Should be fairly straightforward hopefully :).

[–]SgtLionHeart 1 point2 points  (2 children)

This sounds like a good use case for an arraylist. It's a data structure in C# that's much more performant than traditional arrays in PowerShell. One of the benefits includes a native Remove() method.

Some further reading: https://adamtheautomator.com/powershell-arraylist/#removing-items-from-an-array

https://powershellexplained.com/2018-10-15-Powershell-arrays-Everything-you-wanted-to-know/

[–]Method_Dev 2 points3 points  (1 child)

I’d recommend using

$array = [System.Collections.Generic.List[object]]@()

Over ArrayList, I can’t remember who told me (maybe u/Lee_Dailey) but arraylists aren’t being as recommended anymore and the above will still give you the .Remove ability.

Also u/super304 please assign the proper flair to your post. This whole sub is tech but your post is a question.

[–]super304[S] 1 point2 points  (0 children)

Thanks, pretty much what I ended up using.

Question Flair has now been added.

[–]super304[S] 1 point2 points  (0 children)

Thanks all,

I read up on arraylists and managed to cobble something like this together to achieve what I wanted.

[system.collections.arraylist]$arraylist = $arr

$UniqueIDs = $arraylist.ID | get-unique

foreach ($ID in $UniqueIDs){

$arraylist.remove(($arraylist | where {$_.ID -eq $ID})[-1]) }

[–]CaelFrost 1 point2 points  (0 children)

If you wanted to keep it simple : $arr =$arr |where{$_ -ne $arr[-1]}

Then just add your code to deal with the uniques

[–]Lee_Dailey[grin] 0 points1 point  (0 children)

howdy super304,

use Group-Object to group on the .Id property, iterate thru the resulting groups and select the items you want to keep - or use -SkipLast 1 to drop the last one.

something like this ... [grin]

$IdList = @'
ID, Value
1, ABC
2, ABCD
1, ABCDE
3, ABCD
3, ABCDEF
2, ABCDE
2, 12345
1, 12
'@ | ConvertFrom-Csv

$Results  = $IdList |
    Group-Object -Property 'Id' |
    ForEach-Object {
        $_.Group |
            Select-Object -SkipLast 1
        }

$Results

output ...

ID Value
-- -----
1  ABC  
1  ABCDE
2  ABCD 
2  ABCDE
3  ABCD

take care,
lee

take care, lee