Know the difference between sort and sortBy
When it comes to sorting a collection, you can find 2 approaches to do it.
The first is sort
, and this is how Array.sort, ImmutableJs's sort, and several other functions work.
The other approach is sortBy
, which is what Lodash's sortBy, ImmutableJs's sortBy and others use.
But what is the difference?
Let's use a collection of user objects as an example! Each object has a name
and a score
, and we want to order them by the latter.
sort
It gets a comparator function that decides the order of 2 elements. For example, it takes the form of arr.sort((a, b) => ...)
.
It returns a number, and if it's <0 then a
comes before b
, if it's >0, then it comes after. In case the result is 0, they are considered the same.
You don't need to remember the exact API, just know that in order to sort numbers ascending, a - b
is the comparator you'll need.
For our users
example, to sort by score
, use:
users.sort((user1, user2) => user1.score - user2.score)
sortBy
sortBy
, in contrast, gets only one object and converts it to something naturally sortable (think numbers and strings).
To sort the users
by score
, using Lodash's sortBy
:
_.sortBy(users, ({score}) => score)
Using sortBy
usually results in cleaner code, and it is closer to how we think about ordering. If you don't have any specific problems with it, opt for sortBy
.