windchime
windchime

Reputation: 1285

Is there any lodash function to achieve this?

I have an array

var a = [
   {id: 1, item: 3}, 
   {id: 1, item: 4}, 
   {id: 1, item: 5}, 
   {id: 2, item: 6}, 
   {id: 2, item: 7}, 
   {id: 3, item: 8}
]

I need output like this:

[{id: 1, items: [3, 4, 5]}, {id: 2, items: [6,7]}, {id: 3, items: [8]}]

Upvotes: 0

Views: 34

Answers (2)

weirdan
weirdan

Reputation: 2632

It's pretty ugly, but then other answers are not pretty either

var a = [
   {id: 1, item: 3}, 
   {id: 1, item: 4}, 
   {id: 1, item: 5}, 
   {id: 2, item: 6}, 
   {id: 2, item: 7}, 
   {id: 3, item: 8}
];

var ret = _.chain(a)
   
   .groupBy(elt => elt.id)
   .mapValues(elt => _.reduce(elt, (acc, sub) => acc.concat(sub.item),[]))
   .map((value, key) => ({id: key, items:value}))
   
   .value();
console.log(ret);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

Upvotes: 0

Gruff Bunny
Gruff Bunny

Reputation: 27976

Here's a solution that first groups by id and then maps across the groupings to get the required collection:

let result = _(a)
    .groupBy('id')
    .map( (group ,id) => ({id: id, items: _.map(group, 'item')}))
    .value()

Upvotes: 1

Related Questions