Search code examples
javascriptarraysgroupinglodash

How to group the array of object like this ? And remove duplicate?


I am writing a small snippet of JS code which has an array:

[
 { title: 'title1', id: 1 },
 { title: 'title1', id: 2 },
 { title: 'title2', id: 3},
 { title: 'title2', id: 4}
]

I need something like this however:

"queried": {
    "title1": [1, 2],
    "title2": [3, 4],
 }

I am trying to do this with Lodash with _.groupBy(array, "title") but I get:

{ 
 title1:[
  { title: 'title1', id: 1 },
  { title: 'title1', id: 2 }
],
 title2:[
  { title: 'title2', id: 3 },
  { title: 'title2', id: 4 }
],
}

How to fix it please?


Solution

  • Use _.mapValues() to iterate the groups, and _.map() to extracts the values of the ids:

    const lol = [{"title":"title1","id":1},{"title":"title1","id":2},{"title":"title2","id":3},{"title":"title2","id":4}];
      
    const result = _.mapValues(
      _.groupBy(lol, 'title'),
      v => _.map(v, 'id')
    );
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>