lodash orderby method as an option for sorting collections
The lodash orderby method is one of several options in lodash for sorting collections mainly arrays, but also objects in general because it is a collection method rather that just an array method. It works more or less the same way as the lodash sortby method, but it allows for setting the sort orders ( ascending or descending ) of each method that is used to sort the collection object.
1 - lodash orderby basic example
A Basic example of the lodash orderby method could just be passing an array of numbers as the first argument. That kind of example will work the same way as that as such a basic example using lodash sortby.
The second argument is used to give method that are used for sorting, and the third argument is used to set the ascending and descending order of the sorting though. So with that said another basic example the would showcase the difference of orderby compared to sortby would by to set null as the second argument, and then the string ‘desc’ for descending rather than the default ‘asc’ or ascending order.
So then order by is just a more robust version of lodash sortby that allows for setting the ascending or descending order of the resulting sort of the collection.
2 - Using order by with a named key collection
So one thing about the order by method is that it is very much a collection method rather than just an array method. What this measn is that if I am dealing with an naked key collection rather than an array, I can still use the lodash order by method as a way to to create an array of sorted values.
So if I where to use array sort, and I do not want to mutate the original array, then I will want to do something to make a shallow or deep clone of the array first. If I have an array of primitives rather than objects then a way of making a shallow clone will work just fine.
Once I have my copy of the array I can then work out how I would want to go about sorting that copy of an array with a sort method that will be passed as the first argument to the Array.sort prototype method. This method will have two elements to compare given as arguments, and the body of the method should use those arguments to return a delta value for the current index value of the first argument.
4 - Conclusion