原顺序为1, 2, 3, 4, 5;排序后为3, 4, 1, 5, 2
const array = [
{ id: 1, name: 'Object 1' },
{ id: 2, name: 'Object 2' },
{ id: 3, name: 'Object 3' },
{ id: 4, name: 'Object 4' },
{ id: 5, name: 'Object 5' }
];
// 指定顺序的数组
const order = [3, 4, 1, 5, 2];
// 自定义比较函数
function customSort(a, b) {
const indexA = order.indexOf(a.id);
const indexB = order.indexOf(b.id);
return indexA - indexB;
}
// 使用自定义比较函数进行排序
array.sort(customSort);
console.log(array);