From this original question, how would I apply a sort on multiple fields?
Using this slightly adapted structure, how would I sort city (ascending) & then price (
I was looking for something similar and ended up with this:
First we have one or more sorting functions, always returning either 0, 1 or -1:
const sortByTitle = (a, b): number =>
a.title === b.title ? 0 : a.title > b.title ? 1 : -1;
You can create more functions for each other property you want to sort on.
Then I have a function that combines these sorting functions into one:
const createSorter = (...sorters) => (a, b) =>
sorters.reduce(
(d, fn) => (d === 0 ? fn(a, b) : d),
0
);
This can be used to combine the above sorting functions in a readable way:
const sorter = createSorter(sortByTitle, sortByYear)
items.sort(sorter)
When a sorting function returns 0 the next sorting function will be called for further sorting.