According to this answer i have sorted my array of objects by a string property. See this example:
const preData = [
{ type: "veggie", name: "Tomato salad" },
{ type: "veggie", name: "Cole slaw" },
{ type: "veggie", name: "Nothing" },
{ type: "meat", name: "Spare-ribs" },
{ type: "meat", name: "Steak" },
{ type: "meat", name: "Pulled pork" },
{ type: "potato", name: "Pommes frites" },
{ type: "potato", name: "Curly fries" },
{ type: "potato", name: "King size frites" }
];
I tried to sort this by type
and also by name
.
const sortOrder = { meat: 1, potato: 2, veggie: 3 };
const postData = preData.sort((a, b) => (sortOrder[a.type] || Number.MAX_VALUE) - (sortOrder[b.type] || Number.MAX_VALUE) || (a.name.toUpperCase() > b.name.toUpperCase()));
What i expect:
postData = [
{ type: "meat", name: "Pulled pork" },
{ type: "meat", name: "Spare-ribs" },
{ type: "meat", name: "Steak" },
{ type: "potato", name: "Curly fries" },
{ type: "potato", name: "King size frites" },
{ type: "potato", name: "Pommes frites" },
{ type: "veggie", name: "Cole slaw" },
{ type: "veggie", name: "Nothing" },
{ type: "veggie", name: "Tomato salad" }
];
But the second sort fails. It gets sorted by type
, but not by name
.
postData = [
{ type: "meat", name: "Spare-ribs" },
{ type: "meat", name: "Steak" },
{ type: "meat", name: "Pulled pork" },
{ type: "potato", name: "Pommes frites" },
{ type: "potato", name: "Curly fries" },
{ type: "potato", name: "King size frites" },
{ type: "veggie", name: "Tomato salad" },
{ type: "veggie", name: "Cole slaw" },
{ type: "veggie", name: "Nothing" }
]
I know ||
connects multiple sortings, but why isn't it working here?