0

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?

GePu
  • 320
  • 2
  • 13
  • 1
    The compare function should return 0 for equal values. Your compare function is wrong. It returns 0 for the second and third element in your input array. Your compare function never returns negative values when names are compared. Reread https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Thomas Sablik Feb 22 '23 at 15:33
  • `preData.sort((a,b) => sortOrder[a.type] - sortOrder[b.type]);` – 001 Feb 22 '23 at 15:51
  • btw, an assignment assign the original object reference but not a copy of sorted array. – Nina Scholz Feb 22 '23 at 15:53

0 Answers0