So I had a need to compare two arrays if they intersect.
What I wrote
This uses full names for all parameters and Cmdlets. This allows for easy reading of the code. It uses some things that I dont think is needed. For instance -Passthru will just send through the entries and not the “==” for each.
$array1 = @(1, 2, 6, 3, 4, 5)
$array2 = @(2, 4, 3, 1, 0)
(Compare-Object -ReferenceObject $array1 -DifferenceObject $array2 -ExcludeDifferent -IncludeEqual -Passthru).Count -ge 1
LLM suggestions
So I let two LLMs create solutions for the issue.
Copilot
Copilot choose to create a single solution. It works, it is not fancy.
Out of the chatbox
$array1 = @(1, 2, 6, 3, 4, 5)
$array2 = @(2, 4, 3, 1, 0)
$commonItems = $array1 | Where-Object { $_ -in $array2 }
if ($commonItems.Count -gt 0) {
Write-Host "Common items found: $($commonItems -join ', ')"
} else {
Write-Host "No common items found."
}
Okey, it is much bigger. But lets shink it down to the real components.
$array1 = @(1, 2, 6, 3, 4, 5)
$array2 = @(2, 4, 3, 1, 0)
($commonItems = $array1 | Where-Object { $_ -in $array2 }.count -ge 1)
So Copilot was shorter right? I can make mine shorter too, I can Change Where-Object to % too. But writing code that can be read is more valuble than a few characters.
Mine shrinked
$array1 = @(1, 2, 6, 3, 4, 5)
$array2 = @(2, 4, 3, 1, 0)
(compare $array1 $array2 -E -I).Count -gt 0
ChatGPT
So here we get a good suggestion, one of the same kind that Copilot offered and a total hallucination.
Starts good
$commonItems = Compare-Object -ReferenceObject $array1 -DifferenceObject $array2 -IncludeEqual -ExcludeDifferent
$commonItems | ForEach-Object {
if ($_.SideIndicator -eq "==") {
Write-Output $true
return
}
}
Write-Output $false
This started so good. And then I dont know where this headed.
Same as Copilot
($array1 | Where-Object { $array2 -contains $_ }).Count -gt 0
This works a little better than Copilot, I know it is history. But -in is newer than -contains. So -contains is more backwards compatible.
Hallucination
So this looks like a really smart solution. Short consise.. But there is no .Any() operator.
$array1.Any({ $array2 -contains $_ })