5

I have two arrays that I want to compare the items of

I have array A [hi,no,lo,yes,because] and array B [mick,tickle,fickle,pickle,ni,hi,no,lo,yes,because]

so I want to search every item in A and compare to every item in B and if there is a match return "there is a match"

2
  • 2
    What have you tried? What errors have you gotten? Please show what efforts you have made so that we can help fix things, we don't just hand out code without some effort on your part. Commented Jun 18, 2014 at 16:40
  • I'm not sure what you're asking. Do you want to know if A is found inside B, with items in sequence, or do you want to know if all of the items are in B, but not neccessarily in sequence? Or do you want to know if the arrays are the same, and in sequence? Be more specific. Commented Jun 18, 2014 at 16:50

1 Answer 1

11

One-liner:

foreach ($elem in $A) { if ($B -contains $elem) { "there is a match" } }

But it may be more convenient to count matches:

$c = 0; foreach ($elem in $A) { if ($B -contains $elem) { $c++ } }
"{0} matches found" -f $c

Or if you want to check if arrays intersect at all:

foreach ($elem in $A) { if ($B -contains $elem) { "there is a match"; break } }

Or if you want to check if $A is a subset of $B:

$c = 0; foreach ($elem in $A) { if ($B -contains $elem) { $c++ } }
if ($c -eq $A.Count) { '$A is a subset of $B' }

Finally there's Compare-Object cmdlet which is actually better than all of the above. Example (outputs only elements that are present in both arrays):

Compare-Object -IncludeEqual -ExcludeDifferent $A $B
Sign up to request clarification or add additional context in comments.

1 Comment

You could have started with the compare-object :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.