2

I have 2 arrays: I need to sort them in foreach to modify 1 file.

1 array with dbs name like:

$dbs = ['Honda', 'Toyota', 'BMW', 'Opel']

2nd array with their size like:

$dbsSize = ['123', '300', '222', '143']

and I can sort names in foreach like

foreach ($db in $dbs){
  # some logic..
}

How can I sort 2nd array in the same foreach so I can use it in the same loop

Like this:

foreach ($db in $dbs) {
  # some logic with $db
  # and here I need some logic with $dbsSize 
}

but to sort out $dbsSize like $dbs because I need the result like :

Honda
123

Toyota
300

etc.

Do I need to create another loop?

mklement0
  • 382,024
  • 64
  • 607
  • 775
Sergio Ramos
  • 93
  • 1
  • 6

2 Answers2

1

I don't see any sorting in your code, I only see enumeration. Seems like you want to enumerate both collections sequentially, in that case you would need to use a for loop instead of foreach:

$dbs = "['Honda', 'Toyota', 'BMW', 'Opel']" | ConvertFrom-Json
$dbsSize = "['123', '300', '222', '143']" | ConvertFrom-Json

for($i = 0; $i -lt [math]::Max($dbs.Count, $dbsSize.Count); $i++) {
    $dbs[$i]
    $dbsSize[$i]
}

If you want to use a foreach loop and both collections have the same Length, then you can get the items of one of them (your choice which) via indexing [ ]:

$i = 0
foreach($item in $dbs) {
    $item
    $dbsSize[$i++]
}

If you're looking to merge both arrays into objects, an easy way to do it is with the function from this answer, the usage in this case would be:

$dbs, $dbsSize | Join-Array -Columns Car, Size
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
1

It seems to me you have two arrays where the indices determine which element of the one array belongs to the element in the other array.

It is unclear how you created them and why you did not create an array of objects with both properties together in the first place, but you can still do that like this:

$dbs     = 'Honda', 'Toyota', 'BMW', 'Opel'
$dbsSize = '123', '300', '222', '143'

$result = for($i = 0; $i -lt [math]::Max($dbs.Count, $dbsSize.Count); $i++) {
    [PsCustomObject]@{
        Car  = $dbs[$i]
        Size = $dbsSize[$i]
    }
}

# sort the items on 'Car' for instance
$result = $result | Sort-Object Car

# show on screen
$result

# save to structured CSV file you can open in Excel
$result | Export-Csv -Path 'X:\Somewhere\cars.csv' -UseCulture -NoTypeInformation

Result on screen using the above exampe looks like

Car    Size
---    ----
BMW    222 
Honda  123 
Opel   143 
Toyota 300
Theo
  • 57,719
  • 8
  • 24
  • 41