Q:

Sort array of objects by list of defined values array in JavaScript

I have array of objects like:
[
    { hour: "08:00" },
    { hour: "08:30" },
    { hour: "09:00" },
    { hour: "09:30" },
    { hour: "10:00" },
]

and list of "priorities":
[
    "09:00",
    "09:30",
    "12:00" // Yes, it doesn't exist in array of available hours
]

I'd like have output of the function:
[
    { hour: "09:00" },
    { hour: "09:30" },
    { hour: "08:00" },
    { hour: "08:30" },
    { hour: "10:00" },
]

I think I could use .sort with own compare function in JavaScript, but I don't have any idea how can I even start with this problem.
I'll be grateful for any tips for solving my problem.

A:

you can do it with sort in one go ... with a reversed priority list to make it easy ... i.e. the highest priority has the highest indexOf, and anything not in the list has a priority of -1

const data = [
    { hour: "08:00" },
    { hour: "08:30" },
    { hour: "09:00" },
    { hour: "09:30" },
    { hour: "10:00" },
]

const priorities = [
    "09:00",
    "09:30",
    "12:00" // Yes, it doesn't exist in array of available hours
];
const reverse = priorities.slice().reverse();

let result = data.sort((a, b) => {
    prioritya = reverse.indexOf(a.hour);
    priorityb = reverse.indexOf(b.hour);
    if (prioritya === priorityb) {
        return a.hour.localeCompare(b.hour);
    }
    return priorityb - prioritya;
});
console.log(result);

