In lodash there is a useful collection method called _.groupBy that can be used to created an object that has keys where each each key is a group that meets some kind of conditions defined in a function that is given to it. In other words in can be used to group things together, this post will show some examples of _.groupBy in action.
The _.groupBy method is one of the many collection methods in lodash meaning that it can be used with any object in general, not just Arrays. So the first argument given to it can be an Array, an Array like object, or just any Object, and then the second argument is the method that will be used to group the elements in the array. Whatever is returned by the method, is what will be used as a key for an array that will store the one or more elements that belong to that key, depending on the conditions defined in the method.
To start off with a very basic example, say you have a simple array of numbers, and you just want to split them into two groups one where the number is below a certian value and as such belongs to a ‘fail’ group, and all other numbers then end up falling into a ‘pass’ group.
When this is called the method given to _.groupBy is called for each element in the array, the value can the be subjected to conditions, or any body of code that is placed in the method that will ultimately be used to return a value that will be used as a key to group the item.
For a slightly more advanced example that still involves an array of numbers, why not group some numbers by the base of one or more numbers. That is have a method that will group an array of numbers by a given array of bases, where a number in the collection will be check if it is the base of the first number in the array of bases, and so forth untill a base is found, or end up defaulting to a ‘none’ key.
So now this is a pretty fun, and useful method that can be used in a lot of different ways. notice that in this example I am also using _.round to round the values that will be set to log to a given precision this helps with a problem where I end up with numbers like 3.0000000001 when finding the power of a number relative to a base. Also note that even methods like _.forEach have little tricks that make them a little more robust compared to the native Array.forEach equivalent, as I can return true to break the forEach loop.
For a more interesting example say you are a student that is taking some classes, you know a number grade for each grade, but you want to group all your clasees by a