Skip to content
Advertisement

Javascript sort array of objects using array of priority

I have this array of objects:

var eventList = [
    {
        eventName: "abc",
        status: "completed"
    },
    {
        eventName: "def",
        status: "live"
    },
    {
        eventName: "ghi",
        status: "live"
    },
    {
        eventName: "jkl",
        status: "upcoming"
    },
]

I want to sort these array of objects using a priority array of a specific key, say ["live", "upcoming", "completed"] for status, meaning all live events come first, followed by upcoming followed by completed. Answers all over the internet seem like you can only sort array objects using keys as ascending or descending. How to I approach this?

Advertisement

Answer

You could do it using Array.prototype.sort() method with an ordering array.

const eventList = [
  {
    eventName: 'abc',
    status: 'completed',
  },
  {
    eventName: 'def',
    status: 'live',
  },
  {
    eventName: 'ghi',
    status: 'live',
  },
  {
    eventName: 'jkl',
    status: 'upcoming',
  },
];

const order = ['live', 'upcoming', 'completed'];
eventList.sort((x, y) => order.indexOf(x.status) - order.indexOf(y.status));
console.log(eventList);

If you would want to make index searching faster when sorting you could use Map Object.

const eventList = [
  {
    eventName: 'abc',
    status: 'completed',
  },
  {
    eventName: 'def',
    status: 'live',
  },
  {
    eventName: 'ghi',
    status: 'live',
  },
  {
    eventName: 'jkl',
    status: 'upcoming',
  },
];

const order = ['live', 'upcoming', 'completed'];
const map = new Map();
order.forEach((x, i) => map.set(x, i));
eventList.sort((x, y) => map.get(x.status) - map.get(y.status));
console.log(eventList);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement