more uses of `_.groupby`

2019-06-20

 | 

~2 min read

 | 

254 words

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 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.



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!