0

Similar to Removing duplicate values from a PowerShell array I want to remove elements from an array. The issue is, I actively work with the end of the array so I want to keep the last instance of a duplicate. | select -uniq removes duplicates that come after it in an array.

Example (Taken from above link modified a little bit):

$a = @(1,2,5,3,0,4,5,6,2,7,8,9,0) $a = $a | select -uniq

Output for $a:

1,2,5,3,0,4,6,7,8,9

But the desired output I'm looking for:

1,3,4,5,6,2,7,8,9,0

Essentially I want leave the last instance of a duplicate.

Thank you!

Community
  • 1
  • 1
user3585839
  • 1,459
  • 3
  • 12
  • 18

1 Answers1

3

One option is to reverse the array so that select -unique is effectively working in reverse, then reverse the result to normalize it.

$a = @(1,2,5,3,0,4,5,6,2,7,8,9,0)
[array]::Reverse($a)
$a = $a | select -unique
[array]::Reverse($a)
$a -join ','
1,3,4,5,6,2,7,8,9,0
mjolinor
  • 66,130
  • 7
  • 114
  • 135
  • Or `($a[$a.length..0] | select -uniq)[$a.length..0]` for quick runs in the console. –  Apr 22 '15 at 15:45