user8179295
user8179295

Reputation:

Sort and delete duplicates in multidimensional array

I have an multidimensional Array and want to sort it by the date and delete the duplicate entries (by date).

$arrayPlaces = [System.Collections.ArrayList]@()

and that is how the Array looks like:

$arrayPlaces.Add(($mailBarcodeInformation[2], $mailScannedStart.Substring(22), "", "", "", "", "", ""))

The empty fields are filled later. The second field $mailScannedStart.Substring(22) is the time and the Array should be sorted by that and the duplicates should also be removed.

I searched a lot but couldn't find any help.

Upvotes: 0

Views: 3344

Answers (1)

woxxom
woxxom

Reputation: 73616

A common approach is to add a custom object into an array and use the buit-in cmdlet sort -unique. It's much more readable:

$arrayPlaces = [System.Collections.ArrayList]@()
#.........
$arrayPlaces.Add([PSCustomObject]@{
    barcode = $mailBarcodeInformation[2]
    time = $mailScannedStart.Substring(22)
    foo1 = ''
    foo2 = ''
    foo3 = ''
}) >$null
#...........
$sorted = $arrayPlaces | sort time -Unique


However, since you already use a .NET class you can switch to a fast .NET SortedDictionary, which automatically sorts and deduplicates the collection when items are added:

$arrayPlaces = [Collections.Generic.SortedDictionary[string,array]]@{}

Adding and overwriting the old value:

$key = $mailScannedStart.Substring(22)
$arrayPlaces[$key] = $mailBarcodeInformation[2], $key, "", "", "", "", "", ""

Checking for presence of an item using its key:

if ($arrayPlaces.ContainsKey($key)) { ....... }

Removing:

[void]$arrayPlaces.Remove('foo')

Accessing:

$items = $arrayPlaces['foo']
$item = $arrayPlaces['foo'][0]

Enumerating (faster):

foreach ($items in $arrayPlaces.Values) {
    # .........
}

Enumerating/pipelining (slower):

$arrayPlaces.Values | foreach { $_[0] = $_[1] + $[2] }

Upvotes: 2

Related Questions