Sorting items in an array by an arbitrary order

Sometimes you need to display data that you fetch from backend in a custom order in frontend. The following snippet shows how to order objects in our array using a custom order defined in another array. Note that to avoid mutation we need to use WEB API's structuredClone() method instead of spread syntax (...) as spread syntax only does a shallow copy of array items and hence won't be able to clone objects inside an array.

const myArray = [
  {name: 'firstname', value: 'Tom'},
  {name: 'age', value: 61},
  {name: 'lastname', value: 'Cruise'}
];
const mySortOrder = ['firstname', 'lastname', 'age'];
const sortArray = (myArray, mySortOrder) => {
  myArray.sort((a, b) => {
    const indexA = mySortOrder.indexOf(a.name);
    const indexB = mySortOrder.indexOf(b.name);
    return indexA - indexB;
  });
  return myArray;
}
const sortedArray = sortArray(structuredClone(myArray), mySortOrder);
console.log(sortedArray);