I am trying to return a list of sorted products:
return products.sort(getSortFunc(activeSortId))
Each activeSortId
corresponds to a sorting callback function which is retrieved by calling getSortFunc
. I have three sorting function: sortByPriceAsc, sortByPriceDesc, sortByDate.
The problem: When the user sortByPriceDesc followed by sortByDate the result is (logically) sorted by descending price still. I would however like it to be sorted by ascending price. I could solve this by chaining the sorting function (return products.sort(a).sort(b).sort(c)
), but what if I don't know the order?:
I'm wondering if I can solve it by calling e.g. sortByPriceAsc within the function sortByDate, or something similar? Below is a simplified attempt, but obviously it does not work because calling sortByPriceAsc doesn't modify anything:
sortByPriceAsc: (a, b) => a.price - b.price,
sortByDate: (a, b) => {
this.sortByPriceAsc()
return b.date - a.date
}
Glad for any help or general critique.