# Combining Arrrays and removing dups

Morning all, I’m just looking for an explanation here. It involves how to properly join arrays. If I do

```\$array1 = 1,2
\$arra2 = 2,3,4
\$array3 = @(\$array1, \$array2)
\$array3 | select -unique```

Then I get a result of 1,2,2,3,4

But if I do

```\$array1 = 1,2
\$arra2 = 2,3,4
\$array3 = \$array1+\$array2
\$array3 | select -unique```

I’ll get what I want as 1,2,3,4

I know its my lack of understanding, but was hoping for a quick education on this.

Appreciate it.

In the first one, you create an array that contains two arrays… A jagged array.

\$array3[0] is array1 and \$array3[1] is array2.
Length of array3 is 2.
First element of array1 is \$array3[0][0]

In the second, you create a flat array, with the length of 5.

phansen nailed it, indeed!

For reference, when doing this sort of thing with large collections that you need to get unique values out of, you can often simply combine the arrays and then cast to a HashSet<T> – this is a generic object type that can hold any one specific defined type of objects, and this cast will automatically remove duplicates as a Hashset can only contain unique values.

Thanks all I appreciate it. If I wanted to take this a bit further how would I accomplish the below?

Combine two arrays, do a compare on the arrays for matches and then remove an entry?

So using the previous example

```\$array1 = 1,2
\$arra2 = 2,3,4
\$array3 = \$array1+\$array2 | select -unique```

Will return the 1,2,3,4

Then compare to another list of values

```\$masterlist = "1","4"

\$matches = compare-object -referenceobject \$array3 -differenceobject \$masterlist -excludedifferent -includeequal | select -expand inputobject```

I’ll now see a \$matches = 1,4

but If I want to remove, say “4”, how would I do this?

If I use the Hashset, it lists all the items as one argument.

If I try

`\$master.Remove("4")`

I get an error since the array is fixed and cannot be changed.

If I change the \$master to a arraylist and try the .remove I still get an error?

I know i’m a bit out of my element here, but would appreciate any help.

how did you change master to arraylist ?

```\$r = New-Object -TypeName System.Collections.ArrayList
\$r
\$r.Remove(1)
\$r
```

I was trying with the \$matches array, but wasn’t successful.

```[System.Collections.ArrayList]@(\$Master = \$Master)
\$Master.remove(4)```

If \$Master is a defined array, this is how you do it.
[System.Collections.ArrayList]@(\$Master)

Appreciate the help!