Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding duplicates in an array

The following code results in an Array:

[Array]$Object = [PSCustomObject]@{
    P1 = 'Appel'
    P2 = 'Cherry'
    P3 = 'Appel'
    P4 = 'Banana'    
}
$Object += [PSCustomObject]@{
    P1 = 'Good'
    P2 = 'Bad'
    P3 = 'Good'
    P4 = 'Good'
}
$Object += [PSCustomObject]@{
    P1 = 'Green'
    P2 = 'Red'
    P3 = 'Green'
    P4 = 'Yellow'
}
$Object

This generates:

P1         P2         P3       P4                          
--         --         --       --                          
Appel      Cherry     Appel    Banana                      
Good       Bad        Good     Good                        
Green      Red        Green    Yellow 

I'm trying to figure out how I can have it report the duplicates, in this case the desired outcome would be P1 and P3 as they both have the same info in them:

P1      P3                       
--      --                       
Appel   Appel                    
Good    Good                     
Green   Green 

Because the values are not in the same object it's not as simple as using Group-Object to retrieve them. Any help would be appreciated.

like image 478
DarkLite1 Avatar asked Jan 08 '23 01:01

DarkLite1


1 Answers

You could use Group-Object to find duplicate property values in each object by inspecting the value of each entry in the psobject.Properties property:

PS C:\> $Object |ForEach-Object {
    $_.psobject.Properties | Group-Object { $_.Value } | Format-Table
}

Count Name                      Group
----- ----                      -----
    2 Appel                     {string P1=Appel, string P3=Appel}
    1 Cherry                    {string P2=Cherry}
    1 Banana                    {string P4=Banana}


Count Name                      Group
----- ----                      -----
    3 Good                      {string P1=Good, string P3=Good, string P4=Good}
    1 Bad                       {string P2=Bad}


Count Name                      Group
----- ----                      -----
    2 Green                     {string P1=Green, string P3=Green}
    1 Red                       {string P2=Red}
    1 Yellow                    {string P4=Yellow}
like image 107
Mathias R. Jessen Avatar answered Jan 15 '23 18:01

Mathias R. Jessen