This topic contains 7 replies, has 4 voices, and was last updated by
December 7, 2018 at 2:08 pm #128635
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.
December 7, 2018 at 2:29 pm #128640ParticipantPoints: 197Rank: Participant
In the first one, you create an array that contains two arrays... A jagged array.
$array3 is array1 and $array3 is array2.
Length of array3 is 2.
First element of array1 is $array3
In the second, you create a flat array, with the length of 5.
December 7, 2018 at 2:51 pm #128646ParticipantPoints: 457Rank: Contributor
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
— 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.
December 7, 2018 at 4:52 pm #128667
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
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.
December 7, 2018 at 5:34 pm #128670ParticipantPoints: 1,633Rank: Community Hero
how did you change master to arraylist ?
$r = New-Object -TypeName System.Collections.ArrayList $r.Add(1) $r.Add(2) $r $r.Remove(1) $r
December 7, 2018 at 9:45 pm #128738
I was trying with the $matches array, but wasn't successful.
[System.Collections.ArrayList]@($Master = $Master) $Master.remove(4)
December 8, 2018 at 2:07 pm #128804ParticipantPoints: 1,633Rank: Community Hero
If $Master is a defined array, this is how you do it.
December 10, 2018 at 1:38 pm #129006
Appreciate the help!
The topic ‘Combining Arrrays and removing dups’ is closed to new replies.