问题
Is it possible to compare two arrays and remove the values that are equal (if they are at the same index), without iterating through both arrays? Here is an example:
$array1 = @(1,2,3,4,5,6,7,23,44)
$array2 = @(1,1,3,4,5,7,6,23,45)
$array3 = $sudo_compare_function $array1 $array2
where $array3
would now contain an array of indexes where $array2
is different from $array1
array:
(1,5,6,8)
If there isn't something like this, is there an easy way to do something similar without iterating through both arrays?
回答1:
Use the Compare-Object
cmdlet to get an array of differing values:
$array1 = @(1,2,3,4,5,6,7,23,44)
$array2 = @(1,1,3,4,5,7,6,23,45)
$array3 = @(Compare-Object $array1 $array2 | select -Expand InputObject
For comparing just the corresponding indexes you'll have to manually make the comparison:
function Compare-Indexes($a1, $a2) {
$minindex = [math]::Min($a1.Length, $a2.Length)
$maxindex = [math]::Max($a1.Length, $a2.Length)
for ($i = 0; $i -le $minindex; $i++) {
if ( $a1[$i] -ne $a2[$i] ) { $i }
}
for ( $i = $minindex + 1; $i -le $maxindex; $i++ ) { $i }
}
$array1 = @(1,2,3,4,5,6,7,23,44)
$array2 = @(1,1,3,4,5,7,6,23,45)
$array3 = Compare-Indexes $array1 $array2
来源:https://stackoverflow.com/questions/16657743/how-can-i-compare-two-arrays-removing-similar-items-without-iterating-through