DEV Community

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

Collapse
 
vonheikemen profile image
Heiker

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);
Collapse
 
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

Collapse
 
vonheikemen profile image
Heiker

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
someArrWithStuff.map(groupBy('type'));

// a raw promise (if you are one of those)
ipromise.then(groupBy('type'));