I came across this looking for a possible solution using Drupal 10.1, and I got something that seems to be working well. I believe this will also work on Drupal 9, but I have personally not tested it. I combined a couple of the previous solutions together:
function vacancies_views_pre_render(&$view) {
// Reverse the resulting array order
$newResultOrder = array_reverse($view->result);
// Now we have the new order so we can set the indexes for each result row.
$newResultOrder = array_values($newResultOrder);
foreach ($newResultOrder as $key => $row) {
// Set index for each result item since it is now in the correct order.
$row->index = $key;
}
$view->result = $newResultOrder;
}
I also created a ViewExecutable object that I was able to change the order (in my own case) based upon contextual items in an array. You could replace this with whatever order you need them. This was tested and is working on Drupal 10.1 at the moment:
$view = Views::getView('whatever_view_machine_name');
if (is_object($view)) {
$view->setArguments($argsIfYouNeedThem);
$view->setDisplay('default');
$view->preExecute();
$view->execute();
// If $resultOrder was built, handle re-ordering.
// This checks if there was a result order from context (code not shown),
// but this array could be any array with Node ID values in
// the order you need the final results to be in.
if ($resultOrder) {
$newResultOrder = [];
// Get the current results.
$results = $view->result;
// Loop through the final resulting Node ID order.
// (from my example, $resultOrder is an array of Node IDs from context).
foreach ($resultOrder as $newResultNid) {
// Loop through view results to compare order of IDs.
foreach ($results as $result) {
// Get the Node ID so we can compare against our $newResultNid
$currentResultNid = $result->nid;
if ($currentResultNid == $newResultNid) {
$newResultOrder[] = $result;
break;
}
}
}
// Now we have the new order so we can set the indexes for each result row.
$newResultOrder = array_values($newResultOrder);
foreach ($newResultOrder as $key => $row) {
// Set index for each result item since it is now in the correct order.
$row->index = $key;
}
$view->result = $newResultOrder;
}
// Since I am rendering in a twig template, we are setting a variable
// for the view results to be passed back.
$variables['rc_view'] = $view->buildRenderable('default', $args);
}