ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

js将一个数组中的多个对象按照指定顺序排序

2026/9/26 14:20:44 拓冰建站 浏览量
js将一个数组中的多个对象按照指定顺序排序

原顺序为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);