What about:
```php
$variant = $item->getVariant();
if (isset($variants[$variant->getId()]) {
    $variants[$variant->getId()]['quantity'] += $item->getQuantity();
} else {
    $variants[$variant->getId()] = array(
        'variant'  => $variant,
        'quantity' => $item->getQuantity()
    );
}
```
And at rest:
```php
$variants = $this->getVariantQuantities($order);

foreach ($variants as $variant) {
    $this->updateVariantUnits($order, $variant['variant'], $variant['quantity']);
}

$this->removeUnusedUnits($order, $variants);
```
Aaaaand last one:
```php
foreach ($order->getInventoryUnits() as $unit) {
    if (!isset($variants[$unit->getStockable()->getId()])) {
        $order->removeInventoryUnit($unit);
    }
}
```

Isn't this simpler? =)