So I have come to find that I like the lodash _.sortBy method more so than the native Array.prototype.sort method. I do still use it of course when it comes to working with a project where lodash is not part of the stack, it is just that the method works in a way that I find more natural. I will be elaborating what I mean by that in this post.
For a basic example of _.sortBy why not start off with just using it to sort an array of numbers. It does not get more basic than that does it.
To sort an array of numbers by numerical value, I just have to give the array of numbers to _.sortBy. No need to give and method as the second argument.
This is all fine and good for a very basic example of the lodash sort by method, but what if I want to set some kind of condition for sorting? A function can of course be given as a second argument, so lets look at another basic example of that.
I can give a method as a second argument that can be used to define an expression for sorting.
That is all fine and good, but in many projects I am working with an array of objects. So lets look at some more basic examples.
When it comes to an array of objects a property name can be given as a second argument to a number value that will be used t sort the collection. If that does not cut it a function can be given to create and return a numbered value that will be used to sort the collection.
When it comes to finding an item in a collection there is finding a single item, and then there is sorting the collection and taking the top or bottom item of that collection. The lodash _.find method will work okay in most situations depending on the nature of the condition that is used. In some cases it would be better to sort the collection by a condition, and then take the first element.
For example say I have a bunch of blog posts and I want to find the post in my collection of posts that has the highest word count. Using the lodash _.find method in that case, would not work out so well because the nature of condition must be applied to all items in the collection. It is a situation in which there is a value that is unique to just one item, but that value is not known it must be found first in order to know what I am looking for. So a better alternative would be to sort.