I'm trying to remove objects from an array that contain duplicates and only keep the ones with the highest number in TasteCode. The example below is highly simplified, but it shows the problem.
Example:
$Fruits
Name | Color | TasteCode
----- ------ ---------
Apple | Red | 2
Apple | Red | 3
Peer | Green | 0
Banana | Yellow | 1
Banana | Yellow | 0
Banana | Yellow | 3
Desired solution:
Name | Color | TasteCode
----- ------ ---------
Apple | Red | 3
Peer | Green | 0
Banana | Yellow | 3
I've already succeeded in gathering the ones that need to be removed, but it doesn't work out quite well:
$DuplicateMembers = $Fruits | Group-Object Name | Where Count -GE 2
$DuplicateMembers | ForEach-Object {
$Remove = $_.Group | Sort-Object TasteCode | Select -First ($_.Group.Count -1)
$Fruits = Foreach ($F in $Fruits) {
Foreach ($R in $Remove) {
if (($F.Name -ne $R.Name) -and ($F.TasteCode -ne $R.TasteCode)) {
$F
}
}
}
}
Thank you for your help.
tastecodein this data?TasteCodefor that specificFruit.Name. The problem is that in the end there are duplicate rows in the Array because of theForeachon the remove part I think.