Home > Software design >  PowerShell | Optimization search : the matching between the elements of two arrays knowing in advanc
PowerShell | Optimization search : the matching between the elements of two arrays knowing in advanc

Time:11-04

I would like to optimize the process when I match the elements between two arrays (each contains several thousand elements). If the match is found then we move on to the next element instead of continuing to search for another match (which does not exist because each element is unique).

$array1 = @(thousandItemsForExample)
$array2 = @(thousandItemsForExample)

foreach ($array1item in $array1) {
    $object = [PSCustomObject]@{
        property1 = $array1item.property1
        property2 = ($array1 | Where-Object { $_.property1 -eq $array2.property1 } | Select-Object property2).property2
}

I tried to find out if any of the comparison operators had this kind of option but I couldn't find anything.

Thank you! :)

PS : Sorry for my English, it's not my native language...

CodePudding user response:

You do this with the help of a hash table that allows for fast look-ups. Also Group-Object -AsHashtable helps greatly with the construction of the hash table:

$array1 = @(thousandItemsForExample)
$array2 = thousandItemsForExample | Group-Object property1 -AsHashTable -AsString

$result = foreach ($item in $array1) {
    [PSCustomObject]@{
        property1 = $item.property1
        property2 = $array2[$item.property1].property2
    }
}

CodePudding user response:

Create a hashtable and load all the items from $array2 into it, using the value of property1 as the key:

$array1 = @(thousandItemsForExample)
$array2 = @(thousandItemsForExample)

$lookupTable = @{}
$array2 |ForEach-Object {
  $lookupTable[$_.property1] = $_
}

Fetching the corresponding item from the hashtable by key is going to be significantly faster than filtering the whole array with Where-Object everytime:

foreach ($array1item in $array1) {
    $object = [PSCustomObject]@{
        property1 = $array1item.property1
        property2 = $lookupTable[$array1item.property1].property2
    }
}
  • Related