对具有 Object 数组的 JavaScript 数组进行排序

您能否建议我根据部分名称按优先级对以下数组进行排序的最佳方法。我更担心时间复杂度,因为我的数组实际上包含 100 000 条记录。


如果有更好的存储方式,我也可以更改数组结构


[{

    id: 'field1',

    sections: [{

        name: 'Top_Section',

        priority: 3

      },

      {

        name: 'Bottom_Section',

        priority: 3

      }

    ]

  },

  {

    id: 'field2',

    sections: [{

        name: 'Top_Section',

        priority: 2

      },

      {

        name: 'Bottom_Section',

        priority: 4

      }

    ]

  },

  {

    id: 'field3',

    sections: [{

        name: 'Top_Section',

        priority: 1

      },

      {

        name: 'Bottom_Section',

        priority: 1

      }

    ]

  },

  {

    id: 'field4',

    sections: [{

        name: 'Top_Section',

        priority: 4

      },

      {

        name: 'Bottom_Section',

        priority: 2

      }

    ]

  }

];

就像我想根据 Top_Section 对优先级进行排序一样,所以我的预期输出应该如下所示,因为 field3 的优先级为 1,而 field2 的优先级为 2,依此类推。


[

  {

    id: 'field3',

    sections: [

      { name: 'Top_Section', priority: 1 },

      { name: 'Bottom_Section', priority: 1 }

    ]

  },

  {

    id: 'field2',

    sections: [

      { name: 'Top_Section', priority: 2 },

      { name: 'Bottom_Section', priority: 4 }

    ]

  },

  {

    id: 'field1',

    sections: [

      { name: 'Top_Section', priority: 3 },

      { name: 'Bottom_Section', priority: 3 }

    ]

  },

  {

    id: 'field4',

    sections: [

      { name: 'Top_Section', priority: 4 },

      { name: 'Bottom_Section', priority: 2 }

    ]

  }

];


撒科打诨
浏览 165回答 2
2回答

幕布斯6054654

我在这里假设“Top_Section”总是在sections 数组的第一个位置。我还假设只有两种优先级类型:“Top_Section”和“Bottom_Section”let list = [{    id: 'field1',    sections: [{        name: 'Top_Section',        priority: 3      },      {        name: 'Bottom_Section',        priority: 3      }    ]  },  {    id: 'field2',    sections: [{        name: 'Top_Section',        priority: 2      },      {        name: 'Bottom_Section',        priority: 4      }    ]  },  {    id: 'field3',    sections: [{        name: 'Top_Section',        priority: 1      },      {        name: 'Bottom_Section',        priority: 1      }    ]  },  {    id: 'field4',    sections: [{        name: 'Top_Section',        priority: 4      },      {        name: 'Bottom_Section',        priority: 2      }    ]  }];function sortBy(priorityName) {  let priorityPosition = (priorityName == 'Top_Section') ? 0 : 1;    return (a, b) => {    return a['sections'][priorityPosition].priority - b['sections'][priorityPosition].priority;  }}console.log( list.sort(sortBy('Top_Section')) );

潇潇雨雨

让我们创建一个比较器function compare(a, b) {    var sumA = 0;    var sumB = 0;    for (var section of a.sections) sumA += section.priority;    for (var section of b.sections) sumB += seciton.priority;    return sumB - sumA;}arr.sort(compare);如果第一个参数较大,比较器返回正数,如果第二个参数较大,则比较器返回负数,如果它们相等,则返回 0。我假设优先级总和的数值越小,项目越大。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript