Here's a JavaScript object,
const obj = {a: [{ id: 1 }, {id: 1}, {id: 2}, {id: 3}], b: [{ id: 4 }, {id: 5}, {id: 5}, {id: 6}] };
and here's a code that correctly groups the items by .id
in each of the two arrays ojb.a
and obj.b
,
const res1 = _.map(obj, x => _.groupBy(x, 'id'));
the result being
[
{
1: [{id: 1}, {id: 1}],
2: [{id: 2}],
3: [{id: 3}]
},
{
4: [{id: 4}],
5: [{id: 5}, {id: 5}],
6: [{id: 6}]
}
]
The lambda, however, is in fact just the partial application of _.groupBy
to its second argument, which is set to 'id'
, so I thought something like this should work,
const res2 = _.map(obj, _.partialRight(_.groupBy, 'id'));
or at least something like this
const res2 = _.map(obj, _.partialRight(_.groupBy, x => x.id));
however, neither of them works, both resulting in this object:
[
{
undefined: [{id: 1}, {id: 1}, {id: 2}, {id: 3}]
},
{
undefined: [{id: 4}, {id: 5}, {id: 5}, {id: 6}]
}
]
Why is that? Is it a bug in lodash
? Or is it because of how JavaScript works? In the latter case, what's happening?
I've found an existing question + self-answer which gives a solution for making the code above work:
const res2 = _.map(obj, _.ary(_.partialRight(_.groupBy, 'id'), 1));
However part of my question is still not answerd: why do I need to use _.ary
? Why doesn't my initial attempt work?