Sorting an array of objects by multiple fields can be tricky. Even worse, the code can be tough to follow and making changes in the future is complicated by conditional logic in the sorting function. In this lesson we'll see how to simplify this using Ramda's
sortWith along with
descending. We'll sort an array of objects by multiple fields and the code will be readable and dead simple to change.
I'm using destructuring to pull a few utility functions in from Ramda. I have some sample data that consists of an array of objects, each object representing a person with a name, age, and height.
I'm logging the array out to the console. I'd like to take this list and I'd like to sort it by each person's age. I'm going to use Ramda's sort, and the first argument for sort is going to be a comparator function, so for that I'm going to use ascend, and then I'm going to pass that call to prop with age.
This is going to send in ascending order by age, and the I pass it my array of data and we'll see our result has been updated. Reese is first, John is last, and then I have a group in the middle where all the ages match. In the cases where the ages match, I'd also like to sort by height in descending order.
I can't do that with sort directly without changing my comparator function, so what I'd like to do is use sortWith instead. Instead of taking a single comparator function, this will take an array of comparators and run them in order.
I'm going to sot ascending by age, and I'm going to use descend to sort in descending order, by height. We'll see that Bob and Allen have been moved above Sally. In a case like Bob and Allen where the age and the height are both the same, I'd also like to sort in alphabetical order.
I'm going to use ascend again, and this time I'm going to sort based on the name prop, and we'll see that Allen and Bob have been switched around, and everybody's in order by age, followed by height, followed by alphabetical by their name.
The great thing about using this setup, is that each comparator is separated, and if I want to change the way this is done, say I want to sort by age then height, all I have to do is take that height comparator, and move it up and my list will be resorted by height, then age, then by name alphabetically.