HomeBlogGithub

Sort array based on another array

Solution

PHP:

function sortBasedOnAnotherArray(array $array, array $sortArray, $property)
{
  $b = $array;
  usort($b, function ($a, $b) use ($property, $sortArray) {
    $A = isset($a[$property]) ? $a[$property] : null;
    $B = isset($b[$property]) ? $b[$property] : null;
    if (array_search($A, $sortArray) > array_search($B, $sortArray)) {
        return 1;
    } else {
        return -1;
    }
  });
  return $b;
}

Javascript:

const sortBasedOnAnotherArray = <T, K extends keyof T>(array: T[], sortArray: T[], key: K): T[] => {
  return [...array].sort((a, b) => sortArray.indexOf(a[key]) - sortArray.indexOf(b[key]))
}
<-- Back to Posts