Reputation: 21
I've a case where multiple arrays need to be compared.There is one master array that contains all the elements that the child arrays have and also some extra elements.
In below example, $a
is the master array and $b
, $c
are child arrays.
I need to compare these arrays and get the list of those extra elements in $a
that are not present in $b
and $c
.
Practically, in my case there are 10 child arrays and a master array.
$a="dhaw","roh","kohl","faf","abd","steyn","gupt","baz","kane","benn","brendn","joyc"
$b="roh","dhaw","kohl"
$c="steyn","abd","faf","roh","dhaw"
Upvotes: 0
Views: 3088
Reputation: 68341
A regex solution:
$a="dhaw","roh","kohl","faf","abd","steyn","gupt","baz","kane","benn","brendn","joyc"
$b="roh","dhaw","kohl"
$c="steyn","abd","faf","roh","dhaw"
$b_regex = ‘(?i)^(‘ + (($b |foreach {[regex]::escape($_)}) –join “|”) + ‘)$’
$c_regex = ‘(?i)^(‘ + (($c |foreach {[regex]::escape($_)}) –join “|”) + ‘)$’
Then, for elements of $a that aren't in $b:
$a -notmatch $b_regex
faf
abd
steyn
gupt
baz
kane
benn
brendn
joyc
For elements of $a that aren't in $c:
$a -notmatch $c_regex
kohl
gupt
baz
kane
benn
brendn
joyc
And for elements of $a that aren't in $b or $c:
$a -notmatch $b_regex -notmatch $c_regex
gupt
baz
kane
benn
brendn
joyc
Note: this is just provided for demonstration for the people who left comments about it. This substantially faster than the -contains / -notcontains
solutions, but for a single instance comparison it's probably overkill. It can produce substantial performance gains inside a loop where you're comparing one array to many other arrays.
Upvotes: 1
Reputation: 6930
Something like this?
Compare-Object -ReferenceObject $a -DifferenceObject ($b + $c)
If you just want to get raw objects:
(Compare-Object -ReferenceObject $a -DifferenceObject ($b + $c) |
Where-Object {$_.SideIndicator -eq '<='}).InputObject
Upvotes: 1
Reputation: 9644
A viable solution could be using -notcontains
operator as suggested by arco444, cycle through $a
array elements and check if they are contained at least in one of the other arrays.
Here is a slice of code
foreach($a_value in $a) {
if (($b -notcontains $a_value) -and ($c -notcontains $a_value)) {
"$a_value is extra"
}
}
Upvotes: 4