I've been reading similar solved problems but couldn't understand how to apply it in my case.
So, I have an unsorted array of objects:
const queues = [
{"floor":2,"direction":"REQUEST_FLOOR"},
{"floor":1,"direction":"REQUEST_FLOOR"},
{"floor":5,"direction":"CALL_DOWN"},
{"floor":8,"direction":"CALL_DOWN"},
{"floor":7,"direction":"REQUEST_FLOOR"},
{"floor":6,"direction":"CALL_DOWN"}
];
I'd like to sort it into:
const queues = [
{"floor":1,"direction":"REQUEST_FLOOR"},
{"floor":2,"direction":"REQUEST_FLOOR"},
{"floor":7,"direction":"REQUEST_FLOOR"},
{"floor":8,"direction":"CALL_DOWN"},
{"floor":6,"direction":"CALL_DOWN"},
{"floor":5,"direction":"CALL_DOWN"},
];
So, the priority rules I want to apply are :
- Sort "REQUEST_FLOOR" first then only "CALL_DOWN".
- Sort "REQUEST_FLOOR" in ascending and "CALL_DOWN" in descending.
I'm able to make it work by separating it into 2 different arrays, sort, then combine it at the end. Here is my code:
const requestFloors = queues.filter(queue => queue.direction === "REQUEST_FLOOR");
const callDownFloors = queues.filter(queue => queue.direction === "CALL_DOWN");
requestFloors.sort((a,b) => a.floor - b.floor);
callDownFloors.sort((a,b) => b.floor - a.floor);
const newQueues = [...requestFloors,...callDownFloors];
Question: Instead of filtering + sorting, I'd like to just use sort(), so maybe something like this:
queues.sort((a,b) => b.direction.localeCompare(a.direction) || a.floor - b.floor );
However, this code sort the the direction correctly, but the problem is it still sorts the floor in ascending for both direction.
How do I achieve the same result by only using sort()? Any helps will be greatly appreciated.