Discussion on: 5 JavaScript functions to add to your utilities library

vonheikemen profile image

If you sprinkle a little "data last" with some partial application and you really got something on the groupBy.

- function groupBy(arr, key) {
+ function groupBy(key, arr) {
+  if(arguments.length === 1) {
+    return groupBy.bind(null, key);
+  }

  return arr.reduce(
   (acc, i) => {
      (acc[i[key]] = acc[i[key]] || []).push(i);
      return acc;
    }, {});

Now you can have a factory of functions:

const groupByType = groupBy('type');
const groupByName = groupBy('name');
// and many more

groupByType(roleModels) // stuff...

// or just call it like a normal person
groupBy('type', roleModels);
orelkan profile image
Orel Kanditan

It's a neat trick, but it's a little YAGNI isn't it? I can't really think of a situation where I would use this

vonheikemen profile image

Is certainly not necessary. You can always wrap the thing in another function.

const groupByType = arr => groupBy(arr, 'type');

It does come handy when callbacks are involve.

// function composition in ramda style
const complexFunc = pipe(someFunc, groupBy('type'), otherFunc);

// when mapping

// a raw promise (if you are one of those)