/* Code Comments */

More Uses Of `_.groupBy`

June 20, 2019

As I wrote previously, the _.groupBy method of Lodash can be really useful.

My original use case for _.groupBy was for one big object, but of course, those principles extend into the case where it’s an array of objects (or object of objects).

For example - imagine an array like so:

let objArr = [
  { id: 'a', val: 1, age: 20 },
  { id: 'b', val: 2, age: 10 },
  { id: 'c', val: 3, age: 40 },
  { id: 'a', val: 4, age: 80 },
]

let grouped = _.groupBy(objArr, el => el.id)

console.log({ grouped })

Now, imagine that the goal is to group by the id within object. Since id isn’t key of the objArr (i.e. the index of the array), I needed to specify more precisely what I wanted to group by. groupBy allows this through its iteratee parameter. In this case, it meant evaluating the id key of the element, but it could also be an evaluation.

Imagine we wanted to group by folks by age and sort them into buckets. For demonstration purposes, we’ll look at above / below 30.

function evaluateAge(person) {
  let groupLabel = ''
  if (person.age < 30) {
    groupLabel = 'Young-ish'
  } else {
    groupLabel = 'Old-ish'
  }
  return groupLabel
}

let groupedAge = _.groupBy(objArr, evaluateAge)
console.log({ groupedAge })

NB: I could also have done el => evaluateAge(el), however, currying means that’s not necessary.

This should have been obvious, but actually took me a bit to wrap my head around.


Stephen Weiss

Thanks for reading! My name's Stephen Weiss. I live in Chicago with my wife, Kate, and dog, Finn.
Click here to see the archives of my weeks in review and sign up yourself!