-1

I have an array of objects, each object has 2 values, priority and name.

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

I would like to sort this array, ordering by priority High to Low, and then within each priority, by name alphabetically.

Ordering alphabetically is easy enough:

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

But how would I sort by priority in the way I want?

Daft
  • 10,277
  • 15
  • 63
  • 105
  • This might help you https://stackoverflow.com/questions/2784230/how-do-you-sort-an-array-on-multiple-columns – Tech Yogesh Oct 17 '18 at 08:49
  • You can use ``_.orderBy`` to have multiple sorting options. Like example provided on lodash document. https://lodash.com/docs/4.17.10#orderBy – Sandip Nirmal Oct 17 '18 at 08:49

2 Answers2

5

You need to create a map for specifying the order of priorities and then can use Array.sort like following

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);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
2

This can be achieved via "sort" as below.

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))
Nitish Narang
  • 4,124
  • 2
  • 15
  • 22