I have a collection of objects that look like this:
// items: [
{type: 'FRUIT', description: 'Apple'},
{type: 'VEGETABLE', description: 'Carrot'},
{type: 'FRUIT', description: 'Banana'},
{type: 'GRAIN', description: 'Rice'},
{type: 'VEGETABLE', description: 'Broccoli'},
]
Currently, I'm arranging these objects using the following function:
const items = items.sort((a, b) => {
if (a.type > b.type) return -1;
if (a.type < b.type) return 1;
return a.description.localeCompare(b.description);
});
The resulting order is as follows:
// items: [
{type: 'VEGETABLE', description: 'Broccoli'},
{type: 'VEGETABLE', description: 'Carrot'},
{type: 'FRUIT', description: 'Apple'},
{type: 'FRUIT', description: 'Banana'},
{type: 'GRAIN', description: 'Rice'},
]
Now, I want to prioritize one specific type, let's say FRUIT, to appear first. Therefore, the desired output should be:
// items: [
{type: 'FRUIT', description: 'Apple'},
{type: 'FRUIT', description: 'Banana'},
{type: 'VEGETABLE', description: 'Broccoli'},
{type: 'VEGETABLE', description: 'Carrot'},
{type: 'GRAIN', description: 'Rice'},
]
I've attempted various solutions found in similar queries without success. Any recommendations or ideas? Is achieving this result feasible?
Appreciate your assistance.
[UPDATED]: After incorporating @Andrew Parks' suggestion, here's my finalized solution:
items.sort((a, b) =>
+(b.type === "FRUIT") -
+(a.type === "FRUIT") ||
a.type.localeCompare(b.type) ||
a.description.localeCompare(b.description)
);