1

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...

  • See also: [In PowerShell, what's the best way to join two tables into one?](https://stackoverflow.com/q/1848821/1701026) – iRon Nov 03 '22 at 16:54

2 Answers2

2

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
    }
}
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
1

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
    }
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206