按自定义字段对对象数组排序,然后按字母顺序排序

时间:2018-10-17 08:46:32

标签: javascript lodash

我有一个对象数组,每个对象都有2个值,优先级和名称。

var people = [
        {
            "name" : "Jim",
            "priority" : "Low"
        },
        {
            "name" : "Gary",
            "priority" : "Medium"
        },
        {
            "name" : "Andrew",
            "priority" : "Medium"
        },
        {
            "name" : "Bill",
            "priority" : "High"
        },
        {
            "name" : "Edward",
            "priority" : "Medium"
        }
    ]

我想对此数组排序,按优先级从高到低排序,然后在每个优先级内按字母顺序排列。

按字母顺序排序很容易:

people = _.orderBy(people, 'name');

但是我将如何按照自己想要的方式对优先级进行排序?

2 个答案:

答案 0 :(得分:4)

您需要创建用于指定优先级顺序的地图,然后可以像下面这样使用Array.sort

let priorityMap = {"High" : 3,"Medium" : 2,"Low" : 1};
let people = [{"name":"Jim","priority":"Low"},{"name":"Gary","priority":"Medium"},{"name":"Andrew","priority":"Medium"},{"name":"Bill","priority":"High"},{"name":"Edward","priority":"Medium"}];
people.sort((a,b) => priorityMap[b.priority] - priorityMap[a.priority] || a.name.localeCompare(b.name));
console.log(people);

答案 1 :(得分:1)

这可以通过以下“排序”来实现。

var people = [
        {
            "name" : "Jim",
            "priority" : "Low"
        },
        {
            "name" : "Gary",
            "priority" : "Medium"
        },
        {
            "name" : "Andrew",
            "priority" : "Medium"
        },
        {
            "name" : "Bill",
            "priority" : "High"
        },
        {
            "name" : "Edward",
            "priority" : "Medium"
        }
    ]
let priority = {"High": 0, "Medium": 1, "Low": 2}
people.sort((a,b) => priority[a.priority] - priority[b.priority] || a.name.localeCompare(b.name))