How can I compare two arrays, removing similar items, without iterating through the whole array?

喜欢而已 提交于 2020-01-03 19:09:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!