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

发布时间:2024年01月03日

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

文章来源:https://blog.csdn.net/weixin_46151381/article/details/135368108
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。