Depender and Dependee variable reallignment

Nandan Hegde 36,146 Reputation points MVP Volunteer Moderator
2022-12-13T11:17:34.66+00:00

I am not able to visualize the best way to achieve the below scenario:

I have extracting some data from REST API and based on that I assign values to 2 variables :
$Dependee
$Depender

for eg :
$Dependee=@('a','b')
$Depender=@('c')

this would be done in multiple iterations like :

1st iteration :
$Dependee=@('a','b')
$Depender=@('c')

2nd iteration:
$Dependee=@('a')
$Depender=@('x')

3rd iteration:
$Dependee=@('b')
$Depender=@('y')

4th iteration:
$Dependee=@('m')
$Depender=@('n')

etc

Now I need an output as below:

a is used in c,x
b is used in c,y
m is used in n

how can i achieve this as there are scenarios wherein it becomes a nested array.

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2022-12-14T04:05:33.027+00:00

    This should work:

    $dependancies = @{Dependee=@('a','b'); Depender=@('c')},  
                    @{Dependee=@('a'); Depender=@('x')},  
                    @{Dependee=@('b'); Depender=@('y')},  
                    @{Dependee=@('m'); Depender=@('n')}  
      
    $UsedIn = @{}  
    ForEach ($dependency in $dependancies){  
        ForEach ($dee in $dependency.Dependee){  
            ForEach ($der in $dependency.Depender){  
                    if ($UsedIn.ContainsKey($dee)){  
                        $UsedIn.$dee += $der  
                    }  
                    else{  
                        $UsedIn[$dee] = ,$der       # magic comma!  
                    }  
                }  
        }  
    }  
    $UsedIn  
    

1 additional answer

Sort by: Most helpful
  1. Aung Zaw Min Thwin 306 Reputation points
    2022-12-14T03:14:45.943+00:00

    You can try creating hash table or dictionary on each dependee and store each matching depender as array.
    e.g.

    $htDependee = @{}  
      
    #1st iteration :  
    #$Dependee=@('a','b')  
    #$Depender=@('c')  
    $htDependee['a'] += ,'c'  
    $htDependee['b'] += ,'c'  
      
    #2nd iteration:  
    #$Dependee=@('a')  
    #$Depender=@('x')  
    $htDependee['a'] += ,'x'  
    

    etc

    rgds,


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.