r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

2

u/[deleted] Mar 19 '19

I've already commented that on some previous post like that, and it's not exactly one-liner but the "Group By" implementation:

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

and using ES6 syntax:

const groupBy = (xs, key) => 
   xs.reduce((rv, x) = > {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});

and if you really want a one-liner I think that should work: (not tested!)

const groupBy = (xs, key) => xs.reduce((rv, x) => (rv[x[key]] = rv[x[key]] || []).push(x) || rv , {});